• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/167

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

167 Cards in this Set

  • Front
  • Back

constructor chaining

this design patter is helpful when you have a class that defines multiple constructors.

#this keyword

this keyword provides access top the current class instance.'used to resolve scope ambiguity

if you do not define a custom constructor, the C# compiler will

grant you a default in order to allow the object user to allocate an instance of your type with field data set to the correct default value

Objects must be allocated into memory using the new keyword. If you do not make use of the new keyword and attempt to make use of your class variable in a subsequent code statement you will receive a compiler error. The following Main() method will not compile

static void Main(string[] args) { Console.WriteLine("--------------------"); //error, we need to use new to create object Car myCar; myCar.petName = "Fred"; } ----------------------- static void Main(string[] args) { Console.WriteLine("--------------------"); //Correct Car myCar = new Car(); myCar.petName = "Fred"; }

The ?? Operator

allows you to assign a value to a nullable type if the retried value is in fact null. Example - assume you want to assign a local nullable integer to 100 if the value returned from GetIntFromDatabase() is null DatabaseReader dr = new DatabaseReader(); int myData = dr.GetIntFromDatabase() ?? 100; equivalent using ? int? moreData = dr.GetIntFromDatabase(); if (!moreData.HasValue) moreData = 100;

The 3 core principals of OOP

Encapsulation - how does the language hides an object's internal implementation details and preserve data integrity Inheritance - how does this language promotes code reuse Polymorphism - how does this language let you treat related objects in a similar way

Defining static classes

it is possible to apply the static keyword directly on the class level. When a class has been defined as static, it is not creatable using the new keyword. and it can contain only member or data fields marked with the static keyword

A given class may define only a single static constructor. In other words, the static constructor cannot be ____________

overloaded

A static constructor does not take _________________________

A static constructor does not take an access modifier and cannot take any parameter

How many times a static constructor executes?

Once, regardless of how many objects of the type are created The run-time invokes the static constructor when it creates of the class or before accessing the first static member invoked by the caller

C# demands that a given class have ___________ base class

one hence C# does not have multiple inheritance //Illegal! class WontWork : BaseClassOne, BassClassTwo {}

c# sealed keyword

prevents inheritance from occuring // The MiniVan class cannot be extended! sealed class Minivan : Car { }

c# inheritance

// MiniVan is-a Car class MiniVan : Car {}

readonly field

read-only field data cannot be change after the initial assignment. Unlike constant, the value assigned to a read-only field can be determined at runtime and therefore can legally be assigned within the scope of a constructor class MyMathClass { //Read-only fields can be assinged in ctor, but nowhere else public readonly double PI; public myMathClass () { PI = 3.14; } }

C# partial keyword

Using partial classes, you could choose to move the constructors and field data into a brand new file. Use when a class is thousands of line and it is too unconvenient for one file class Emploee { //field data //constructors } //-------------------- vs //Employee.cs partial class Employee { //field data } //Employee.Internal.css partial class Employee { //constructors }

automatic property syntax

class Car { public stirng PetName { get; set; } public int Speed { get; set; } public string Color { get; set; } }

public c# access modifier

public items have no access restrictions. A public member can be accessed fro man object, as well as any derived class. A public type can be accessed from other external assemblies.

private c# access modifier

private items can only be accessed by the class that defines the item

protected c# access modifier

protected items can be used by the class which defined it, and any child class. However, protected items cannot be accessed from the outside world using the C# dot operator

internal c# access modifier

internal items are accessible only within the current assembly. Therefor, if you define a set of internal types within a .Net class library, other assemblies are not able to make use of htem

protected internal c# access modifier

when the protected and internal keywords are combined on an item, the item is accessible within the defining assembly, the defining class, and be derived classes

virtual member def

is a member of a base class that defines a default implementation that may be changed by derived class

abstract method def

abstract method is a member in a base class that does not provide a default implementation, but does proved a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type

Managed code is executed by _____________



CLR


FCL

Managed code is executed by the Common Language Runtime (CLR) Managed languages depend on services provided by a runtime environment.



CLR - Common Language Runtime


FCL - Framework Class Library

What are Dynamics?

Instructs the compiler to ignore type checking at compile-time Defers type checking until runtime

struct def

public struct Point { public int X { get; set; } public int Y { get; set; } }

When to use structs

-instance of the type are small -the struct is commonly embedded in another type -the struct is logically representing a single value -the value don't change (immutable) -it is rarely "boxed" Structs can have performance benefits in computational intensive applications

Static class

expose static member of the class cannot be instantiated

Abstract class

cannot be instantiated it is actually an incomplete class defines behavior for anyone that inherits from this class

Sealed class

cannot be inherited from

Partial classes

a class definition can be split into multiple source files at compile time, these multiple parts are combined of the used in code generation

internal access modifier

internals - can be accessed by any code in the same assembly, but not from any other assembly.

C# short hand implementation

public class Animal { public string Name { get; set; } private string _name; private string Name { get { return _name; } set { _name = value; } } }

public class Animal { public string Name { get; set; } private string _name; private string Name { get { return _name; } private set { _name = value; } } } What the private in front of set does?

We tell that you cannot change name during the life of the object. It can be set only from within the class but it can be used publicly

default parameters

public class Customer { public int AddPoints(int pointsToAdd =1) { points += pointsToAdd; return points; } } When declaring methods with default values the default method comes as last parameter in the method's signature

named arguments allows to specify arguments in any order allows to easily handle

public class Customer { public int AddPoints(int pointsToAdd, int maxPoints) { points += pointsToAdd; if ( points > maxPoints ) { return maxPoints; } return points; } } usage: int newPoints1 = AddPoint(1, 10); int newPoints2 = AddPoints(maxPoints:10, pointsToAdd: 1); int newPoints3 = AddPoints(1, maxPoints: 10);

public event EventHandler HasSpoken;

event - lets the object to talk back to the developer in an implementation of a method if (HasSpoke != null ) // we check if someone is listening HasSpoken(this, EventArgs.Empty);

Boxing def

boxing is the act of converting a value type to a reference type unboxing is the reverse it requires a cast int count = 1; // the value of count is copied and boxed object countObject = count; count += 1 // countObject(1) is unboxed and copied to count count = (int)countObject;

sample hello world

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace helloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadLine(); } } }

foreach

var list= new[] {1,2,3,4,5,6}; foreach (var item in list) { if (item % 2 == 0) continue; }

use enum

enum Dogs { hund, coly, shepard } var snoopy = Dogs.hund; switch (snoopy) { case Dogs.hund: case Dog.coly: Console.WritLine("hund or coly"); break; }

is operator

C# provides us with the is operator returns true if an objects is an instance of a type

as operator

the as operator attempts to cast an object to a specified type returning the instance cast to the type null if not possible does not raise an exception

string class Substring

var source = "The quick brown fox jumped over the lazy dog"; var value = source.Substring(4,5); // value == quick

string class Concat

var source = "quick"; var value = string.Concat(value, " fox"); // value == quick fox

string class Replace

var source = "The quick brown fox jumped over the lazy dog"; var value = value.Replace("fox","dog"); //value == "quick dog"

string class ToUpper

var source = "quick dog"; var value = value.ToUpper(); // value == "QUICK DOG"

string class ToArray

var src = "dog"; var array = src.ToArray(); // array == {'d', 'o','g'}

string class Split

var source ="The quick brown fox"; var split = source.Split(' '); var value = split[1]; // value = "quick"

How to get the total number of elements in an array?

By using the Length property Numbers.Lenght

What are the access-specifiers available in C#?

private, protected, public, internal, protected internal

Difference between Static and ReadOnly?

Static:A variable that retains the same data throughout the execution of a program. ReadOnly:you can't change its value.

Write a single line of code to read the entire content of the text file.

User following codestring strContent = System.IO.File.ReadAllText(Server.MapPath(~/MyTextFile.txt));

What is the advantage of using System.Text.StringBuilder over System.String?

String Builder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it's being operated on, a new instance is created.

Can a class have static constructor?

Yes, a class can have static constructor. Static constructors are called before when any static fields are executed. These are used to initialize static class members and called automatically before the first instance is created or any static members are referenced. This is also known as before instance constructor. Below is one example of above described theory. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SampApp{class Sample{static int i;static Sample(){i = 10;Console.WriteLine(In Static Constructor);} public Sample(){Console.WriteLine(In Instance Constructor);}public static void Main(){Sample s = new Sample();}}}

What is difference between var and Dynamic ?

Var word was introduced with C#3.5(specifically for LINQ) while dynamic is introduced in C#4.0. variables declared with var keyword will get compiled and you can have all its related methods by intellisense while variables declared with dynamic keyword will never get compiled. All the exceptions related to dynamic type variables can only be caught at runtime.

What is the difference between object pooling and connection pooling?

In case of object pooling, you can control the number of connections. In this case the pool will decide whether the maximum is reached or not for creation of objects. If it reached to the maximum level then the next available object will returned back. The drawback is, it increases the time complexity for heavy objects.In case of connection pooling, you can control the maximum number of connections reached. When you are using this pool, since there is nothing in the pool, still it will create connection on the same thread.

Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, we can allow the class to be inherited without over-riding the method.Just leave the class as public and make the method sealed.

What are the different C# preprocessor directives?

#region,#endregion:- Used to mark sections of code that can be collapsed. #define,#undef:-Used to define and undefine conditional compilation symbols. #if,#elif,#else,#endif:- These are used to conditionally skip sections of source code.

Can you prevent a class from overriding ?

Yes you can prevent a class from overriding if you define a class asSealedthen you can not inherit the class any further.

Why we are using System.Environment class?

The aim of usingSystem.Environmentclass is to get the command-line arguments.This class also helps us to retrieve the environment variable settings for a particular contents of the call stack. It can also find the time of last system boot and version of the CLR.

What is partial class?

Partial class is a new functionality added in since .NET Framework 2.0 version. It allows to split us to split the definition of once class, struct, interface into multiple source files. Each source file contains a section of definition, and all parts are combined when the application is compiled

What is ILDASM?

The ILDASM stands for Intermediate Language Disassembler. This is a de-compiler which helps to get the source code from the assembly.This ILDASM converts an assembly to instructions from which source code can be obtained.The ILDASM can analyze the .dll or .exe files and converts into human readable form. This is used to examine assemblies and understanding the assembly capability.

Explain about abstract property

A property with abstract keyword is considered as abstract property. An abstract property cannot have any implementation in the class. In derived classes you must have to write their own implementation

What is Jagged Array?

An array whose elements are arrays is known as a jagged array.The elements of this jagged array can be of different dimensions and sizes.A jagged array is sometimes called as an array-of-arrays.

What is an ArrayList?

ArrayList is a dynamic array. Elements can be added&removed from an arraylist at the runtime. In this elements are not automatically sorted.

Write an equivalent of exit() for quitting a C# .NET application?

Yes, in case of windows forms application you can exit the application with the help of System.Environment.Exit(datatype exitCode) or Application.Exit().

Where the global assembly cache located on the system?

Usually the global assembly cache located at C:\winnt\assembly or C:\windows\assembly.

What is virtual function?

To provide a specialized implementation in a class, we can mark the member function name as virtual which can be overridden in the subclasses. We can declare methods, indexers, events, and properties as virtual in a class.It implements the concept of polymorphism. If a class that overrides the virtual method then it has to use the override keyword.

What is private constructor? What is the use of it?

Private constructor are the special kind of constructor, which are allowed to not set create instance of a class from outside of the class. They are basically created when a class only have static members.when you want to create a single instance of class than use private constructor, basically they are used for Singlton pattern also.

What is Primary Interop Assembly (PIA)?

This is an assembly that contains the type definitions that is metadata of types, which is implemented with COM. This can snatch up multiple versions of the same type library. These are needs to be signed with a strong name by the publisher of the COM type library. This library imported as an assembly when it has been signed.

Are all methods virtual in C# ?

No. Like C++, methods are non-virtual by default, but those methods can be marked as virtual methods.

Are private class-level variables inherited?

Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

By default which class is inherited by a class in C#?

If no class is inherited, by default a class inherit System.Object.

Can 'this' be used within a static method?

No 'This' cannot be used in a static method. This is because, only static variables/methods can be used in a static method.

Can multiple catch blocks be executed ?

No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

Can we call a base class method without creating instance ?

Yes,It is possible,1) If it is a static method.2) By inheriting from that class.3) From derived classes using base keyword.

Can we create a class private?

No, we can not create a class private, it will give runtime error. Example:private classclassname{}compile time error. class can not be defined as private, protected and internal.

Can we create constructor for static class?

No, we can not create constructor for static class, as it its member are called by class name itself.

can we create instance of an abstract class?

No, we can not create instance of an abstract class.

Can we declare a class as Protected?

No, a class can not be declared as Protected. A class can be declared with only following access modifiers. Abstract Internal Public Sealed Static Extern

Can we declare abstract keyword on fields in a class ?

No we cannot.

Can we declare an array variable with var keyword in C# 3.0?

No, var keyword is used to declare implicitly typed local variable. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. So you can declare a local variable of any type usingvarkeyword but you can't declare an array of variable using var keyword.

Can we define generics for any class?

No, generics is not supported for the classes which does not inherits collect class.

Can we force Garbage Collector to run ?

Yes we can,It is Possible to force Garbage Collector this can be done by calling a method called Collect().But this makes a performance barrier since this is not a good programming practice.Generally we have no control over garbage collector when it runs. The main work of this GC is it checks if there are any objects which are not used by the application it calls a Destructor which frees the memory allocated to that unused objects.

Can we inherit a private class into the public class?

No, In C#, a derived class can't be more accessible than it's base class. It means that you can't inherit a private class into a public class. So always the base class should be more or equal accessible than a derived class.

Can we Inherit the class defined with private constructor?

No, we can not inherit the class defined with private constructor.public class A:B{}public class B{private B(){}}Here if we will compile this code error will come:Namespace.B.B() is inaccessible due to its protection level

Can we overload static constructors?

No, static constructors are parameter less constructors and so they cannot be overloaded. Static constructors are called before any other class members are called and called once only. Their main purpose is to initialize only the static members of a class.

Difference between Abstract class and interface?

1.Through the abstract class we cannot achieve the multiple inheritance in c-sharp. while by interface we can.2. We can declare the access modifier in abstract class but not in interface. Because by default everything in interface is public

Difference between static variable and constant in c#?

Static Variable:1.Variable set at run time 2.Can be assigned for reference types. 3.Initialized on constructors Constant: 1.Variable set at compile time itself. 2.Assigned for value types only 3.must be initialized at declaration time 4.only primitive data types.

What is Microsoft Intermediate Language (MSIL)?

A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL - since our source code in automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language, which is, then run on the host machine. MSIL is similar to Java Byte code.MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects.Combined with metadata and the common type system, MSIL allows for true cross- language integration Prior to execution, MSIL is converted to machine code. It is not interpreted.

What is IDisposable interface in .NET?

IDisposable interface is used to release the unmanaged resources in a program.The garbage collector has no knowledge of unmanaged resourcessuch as window handles, or open files and streams.To release these type of resources we make use of the Dispose method by implementing the IDisposable interface.IDisposable interface, defines a single method named Dispose():public interface IDisposable{void Dispose();}

What is HashTable?

A Hashtable is a collection of key-value pairs. Entries in this are instance of DictionaryEntry type. It implements IDictionary, ISerilizable, IDeserializable callback interface.

What is dynamic keyword ?

Its newly introduced keyword of C#4.0. To indicate that all operations will be performed runtime.

What is difference between throw and throw ex?

When you use throw ex to throw exception, it will update stack trace but in throw it will not update stack trace

What is difference between read only and const variable?

A const field can only be initialized only at declaration time of that field but read only field can be initialized at the time of declaration or in constructor also. a const field will have only one constant value but read only field can have different value depending on the constructor. Read only is runtime constant and cons field is compile time constant.

What is Delegates?

A delegate in C# allows you to pass method of one class to objects of other class that can call these methods.ORA delegate is an object that holds the reference to a method.In C++ it is called function pointer.

What is Co-Variance in C#4.0? Explain with example

Converting from a broader type to a specific type is called co-variance.

What is CLS-Compliant?

CLSCompliant attribute on an assembly (or a program element) and have the compiler check if your code is CLS (Common Language System) compliant. This means it works properly when consumed by other .NET languages.

What is BitArray?

The BitArray collection is a composite of bit values. It stores 1 or 0 where 1 is true and 0 is false. This collection provides an efficient means of storing and retrieving bit values.

I want to format these number: 123456 to look like this: 1,234.56. Which expression accomplish this? a)string.Format("0:C}", 12345); b)string.Format("0:N}", 12345); c)string.Format("0:P}", 12345); d)string.Format("0:#,###.##}", 12345);

d

Which of the following is not a method available to the string data type? a)ToUpper() b)Append() c)Replace() d)Trim()

b

#1: When to Use a struct vs Class

structs are value types that can contain data and functionsstructs are value types and do not require heap allocation. structs directly store their data in the struct, classes store a reference to a dynamically allocated object. structs are useful for small data structures structs can affect performanceConstructors are invoked with the new operator, but that does not allocate memory on the heapA struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessaryWith classes, multiple variables may have a reference to the same objectIt is possible for operations on one variable to affect the object referenced by the other variable.With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. structs do not support user-specified inheritance, and they implicitly inherit from type object



everything in .NET is an object of a specific class that derives from the root class called

System.Object

CLS

CLS Common Language Specification (CLS), which provides a series of basic rules that are required for language integration. The CLS determines the minimum requirements for being a .NET language. Compilers that conform to the CLS create objects that can interoperate with one another. The entire Framework Class Library (FCL) can be used by any language that conforms to the CLS.

the .NET Framework consists of Four official languages

the .NET Framework consists of Four official languages: C#, VB .NET, Managed C++, and JScript .NET

the .NET Framework consists of:

Four official languages: C#, VB .NET, Managed C++, and JScript .NET
The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share
A number of related class libraries, collectively known as the Framework Class Library (FCL).

the layer on top of the CLR is a set of framework base classes, followed by an additional layer of data and XML classes, plus another layer of classes intended for web services, web forms, and Windows forms.

Collectively, these classes are known as the Framework Class Library (FCL), one of the largest class libraries in history and one that provides an object-oriented API to all the functionality that the .NET platform encapsulates. With more than 5,000 classes, the FCL facilitates rapid development of desktop, client/server, and other web services and applications.

In .NET, programs are not compiled into executable files; they are compiled into

Microsoft Intermediate Language (MSIL) files, which the CLR then executes



files that C# produces are identical to the IL files that other .NET languages produce

Just In Time (JIT)

C# code is compiled into IL when you build your project. The IL is saved in a file on disk. When you run your program, the IL is compiled again, using the Just In Time (JIT) compiler (a process often called JIT'ing). The result is machine code, executed by the machine's processor.

C# language was developed by

Anders Hejlsberg and Scott Wiltamuth

In C#, a class can inherit from _____________ parent/s

In C#, a class can inherit from only a single parent, but a class can implement multiple interfaces.



When it implements an interface, a C# class in effect promises to provide the functionality the interface specifies.

In C#, a struct is a

In C#, a struct is a restricted, lightweight type that, when instantiated, makes fewer demands on the operating system and on memory than a conventional class does. A struct can't inherit from a class or be inherited from, but a struct can implement an interface.

assembly def

An assembly is a collection of files that appear to the programmer to be a single dynamic link library (DLL) or executable (EXE). In .NET, an assembly is the basic unit of reuse, versioning, security, and deployment. The CLR provides a number of classes for manipulating assemblies

"Hello World" program in C#

using System;


namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello World");


// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

Hold C# application

using System;


namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello World");


// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

namespace.

A namespace restricts a name's scope, Rather than writing the word System before Console, you could specify that you will be using
types from the System namespace by writing the statementmaking it meaningful only within the defined namespace.

Rather than writing the word System before Console, you could specify that you will be using types from the System namespace by writing the statement

using System;

Is C# case sensitive

Yes

static void Main( )



the static keyword indicates

The static keyword indicates that you can invoke Main( )without first creating an object of type Hello.

intrinsic types

intrinsic (built-in) types that the language offers and user-defined types that the programmer defines

value types vs reference types

The principal difference between value and reference types is the manner in which their values arestored in memory. A value type holds its actual value in memory allocated on the stack (or it is allocated as part of a larger reference type object). The address of a reference type variable sits onthe stack, but the actual object is stored on the heap.

C# also supports C++ style pointer types, but

these are rarely used, and only when working with unmanaged code. Unmanaged code is code created outside of the .NET platform, such as COM objects.

Byte


Char
Boolean


Sbyte


Int16


Uint16


Uint32

Byte - size 1 - Unsigned (values 0-255).
Char - size 1 - Unicode characters.
Boolean - size 1 - true or false.
Sbyte - size 1 - Signed (values -128 to 127).
Int16 - size 2 Int16 - Signed (short) (values -32,768 to 32,767).
Unit16 - size 2 - Uint16 Unsigned (short) (values 0 to 65,535).
Int32 - size 4 - Int32 Signed integer values between -2,147,483,647 and 2,147,483,647.
uint 4 Uint32 Unsigned integer values between 0 and 4,294,967,295.

Single


Double


Decimal


Int64


Uint64

Single - size 4 - Floating point number.


Double - size 8 - Double-precision floating point;


Decimal - size 8 - Fixed-precision up to 28 digits and the position of the decimal point. This is typically used in financial calculations. Requires the suffix "m" or "M."


Int64 - size 8 - Signed integers ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.


Uint64 - size 8 - Unsigned integers ranging from 0 to 0xffffffffffffffff.

stack def

stack is a data structure used to store items on a last-in first-out basis (like a stack of dishes at the buffet line in a restaurant). The stack refers to an area of memory supported by the processor, on which the local variables are stored.



In C#, value types (e.g., integers) are allocated on the stack—an area of memory is set aside for their value, and this area is referred to by the name of the variable.



Reference types (e.g., objects) are allocated on the heap. When an object is allocated on the heap its address is returned, and that address is assigned to a reference.

garbage collector

garbage collector destroys objects on the stack sometime after the stack frame they are declared within ends. Typically a stack frame is defined by a function. Thus, if you declare a local variable within a function the object will be marked for garbage collection after the function ends.



Objects on the heap are garbage collected sometime after the final reference to them is destroyed.

Implicit conversions

Implicit conversions happen automatically



short x = 5;
int y = x; // implicit conversion



The compiler will not perform an implicit conversion from int to short:
short x;
int y = 500;
x = y; // won't compile

Explicit conversions happens

Explicit conversions happen when you "cast" a value to a different type.

substitution parameter

System.Console.WriteLine("After assignment, myInt: {0}", myInt);



location of the substitution parameter {0} specifies where the value of the first output variable, myInt, will be displayed, in this case at the end of the string.

An enumeration begins with the keyword enum, which is generally followed by an identifier, such as:
enum Temperatures

The base type is the underlying type for the enumeration. If you leave out this optional value (and often you will) it defaults to integer, but you are free to use any of the integral types (e.g., ushort, long) except for char. For example, the following fragment declares an enumeration of unsigned integers (uint):
enum ServingSizes :uint
{
Small = 1,
Regular = 2,
Large = 3
}

C# (like C and C++) offers two flavors of the increment and decrement operators: prefix and postfix

firstV = secondV++; //postfix assign then incr


firstV = ++secondV; //prefix incr then assign



C# provides a mechanism for declaring that a field holds a constant value, and will never, ever change

const double kilometersPerMile = 1.609344;



The platform now takes advantage of the fact that this can never change, and allocates
storage for it only once, no matter how many instances are there.
This isn’t just a storage optimization, though. By making the field const, there’s no danger that someone might accidentally change it for some reason inside another function he’s building in the class—the C# compiler prevents you from assigning a value to a const field anywhere other than at the point of declaration.



Inheritance in C#

class FireChief : Firefighter
{
public void TellFirefighterToExtinguishFire (Firefighter colleague)
{
colleague.ExtinguishFire();
}
}

The is Operator Versus the as Operator

If your design pattern is to test the object to see if it is of the type you need and if so you will immediately cast it, the as operator is more efficient. At times, however, you might want to test the type of an operator but not cast it immediately. Perhaps you want to test it but not cast it at all; you simply want to add it to a list if it fulfills the right interface. In that case, the is operator will be a better choice.

Interface Versus Abstract Class

Interfaces are very similar to abstract classes



in C# you're stuck; you can't inherit from both the Storable abstract class and also the List class because C# does not allow multiple inheritance with classes.
However, C# does allow you to implement any number of interfaces and derive from one base class. Thus, by making Storable an interface, you can inherit from the List class and also from IStorable, as StorableList does in the following example:
public class StorableList : List, IStorable
{
// List methods here ...
public void Read( ) {...}
public void Write(object obj) {...}
// ...
}

struct is a

struct is a simple user-defined type, a lightweight alternative to classes. Structs are similar to classes in that they may contain structors, properties, methods, fields, operators, nested types and indexers

Defining Structs

public struct Location
{
public Location(int xCoordinate, int yCoordinate)


{
xVal = xCoordinate;
yVal = yCoordinate;
}
public int x
{
get
{
return xVal;
}
set
{
xVal = value;
}
}
public int y
{
get
{
return yVal;
}
set
{
yVal = value;
}
}
public override string ToString( )
{
return (String.Format("{0}, {1}", xVal,yVal));
}
private int xVal;
private int yVal;
}

Structs and destructors

Structs cannot have destructors, nor can they have a custom parameterless (default) constructor. If you supply no constructor at all, your struct will in effect be provided with a default constructor which will zero all the data members or set them to default values appropriate to their type

in C#, the new keyword does not always create
objects on the heap.

Classes are created on the heap, and structs are created on the stack. Also, when new is omitted a constructor is never called. Because C# requires definite assignment, you must
explicitly initialize all the member variables before using the struct.

Creating Structs Without new

Location loc1 = new Location(200,300);
the resulting Location object is created on the stack.



The new operator calls the Location constructor. However, unlike with a class, it is possible to create a struct without using new at all. This is consistent with how built-in type variables

interface

interface is a contract that guarantees to a client how a class or struct will behave. When a class
implements an interface, it tells any potential client "I guarantee I'll support the methods, properties, events, and indexers of the named interface

interface keyword

The interface keyword is followed by the name of the interface. It is common (but not required)
to begin the name of your interface with a capital I. Thus, IStorable, ICloneable, IClaudius,
etc.

base-list



interface-body

The base-list lists the interfaces that this interface extends



interface-body is the implementation of the interface

Suppose you wish to create an interface that describes the methods and properties a class needs to be stored to and retrieved from a database or other storage such as a file. You decide to call this interface IStorable

In this interface you might specify two methods: Read( ) and Write( ), which appear in the
interface-body:
interface IStorable
{
void Read( );
void Write(object);
}
The purpose of an interface is to define the capabilities that you want to have available in a class.


For example, you might create a class, Document. It turns out that Document types can be stored in a
database, so you decide to have Document implement the IStorable interface.
To do so, you use the same syntax as if the new Document class were inheriting from IStorable—
a colon (:), followed by the interface name:
public class Document : IStorable
{
public void Read( ) {...}
public void Write(object obj) {...}
// ...
}

Implementing More Than One Interface

interfaces. To do so, you change the declaration (in the base-list) to indicate that
both interfaces are implemented, separating the two interfaces with commas:
public class Document : IStorable, ICompressible

C# extensions methods

C# allows programmers to user static methods as if they were methods from a class's method table, allowing programmers to add methods to an object that they feel should exist on that object and its derivative

C# & type dynamic

type dynamic allows for run-time method binding, allowing for JS like methods calls and run-time object composition

C# & global variables/functions

C# languages does not allow for global variables or functions. All methods and members must be declared within classes.


Static members of public classes can substitute for global variables and functions

Shadowing

local variables cannot shadow variables of the enclosing block unlike c and c++

C# support strongly typed implicit variable declaration with the keyword

var for variable declaration


new[] for impliocitly typed arrays

How to enable method for overriding by a subclass

must use the KW virtual

How to check if today is Monday?

if (DateTime.Now.DayOfWeek == DayOfWeek.Monday) {


// do something


}

Hold console and wait of user to press enter?

Console.ReadLine();

access modifies



public


protected


internal

public - to class or member, no restriction


protected - to member, access limited to the class and derived classes


internal - to class or member, access limited to the current assembly

access modifies



protected internal


private

protected internal - to member, access limited to current assembly and derived types


private - to member, access limited to the class

abstract keyword

can apply to a class


can also apply to members



abstract class cannot be instantiated


Abstract class is designed as a base class

concrete class

Must implement abstract members to make a concrete class

ildasm.exe

Intermediate Language Disassembler utility
allows you to load up any .NET assembly and investigate its contents, including the associated manifest, CIL code, and type metedata

short circuit evaluation (general)

stop evaluating boolean expression as soon as we know the answer
consider: p = (5 > 3) || (4 <+ 2);
the test ($ <= 2) is not performed!

Example of useful case:
p = ( x!= 0) && ((y / x) == 0);

CLR def + expl

CLR - Common Language Runtime

used to locate, load and manage .NET objects
used for memory management, application hosting, coordinating threads and performing security checks

CTS def + expl

CTS - Common Type System
CTS specification fully describe all possible data types and all programming constructs supported by the runtime,
specifies how these entities can interact with each other and details how they are represented in the .NET metadata

CLS

CLS - Common Language Specification
defines a subset of common types and programming constructs that all .NET programming languages can agree on.
If you build .NET types that expose only CLS-compliant feature, you can rest assured that all .NET-aware languages can consume them

Hello World VBA vs C++

Public Module MyApp
Sub Main()
Console.WriteLine("Hello World!")
End Sub
End Module
------------------
#include "stdfax.h"
using namespace System;
int main(array ^args)
{ Console::WriteLine(L"Hello World");
return 0; }

CTS Enumeration def

programming constructs that allow you to group name/value par
enum CharacterType {
Wizard = 100,
Fighter = 200,
Thief = 300
}

CTS Structure Tpes

//A C# structure type
struct Poin {
//Structure can contain fields
public int xPos, yPox;
//Structure can contain parameterized constructor
public Point(int x, int y)
{ xPos=x; yPos=y; }
//Structure may define methods
public void PrintPosition() {
Console.WriteLine("({0},{1})", xPos, yPos);
}
}

CTS class Characteristics
Is the class sealed or not?
Does the class implement any interfaces?
Is the class abstract or concrete?
What is the visibility of this class?

Is the class sealed or not? - Sealed classes cannot function as base class to other class

Does the class implement any interfaces? - An interface is a collection of abstract members that provide a contract between the object and user. The CTS allows a class to implement any number of interfaces

Is the class abstract or concrete? - Abstract classes cannot be directly instantiated, but are intended to define common behaviors for derived type. Concrete classes can be instantiated directly

What is the visibility of this class? - Each class must be configured with a visibility keyword. Controls if the class may be used by external assemblies or only from within the defining assembly.