Notes

1) What is the difference between Value data types and Reference data types ?

A value type is also known as a primitive or simple type.
When a value data type is created, a single space in memory is allocated on the stack and is accessed directly.
Value data types are automatically given a default value of zero (or equivalent) when they are declared.
A reference type is also known as an object type.
When a reference data type is created, memory is allocated on the heap and is not accessed directly. Instead a pointer to the memory location is used.
Reference data types are automatically given a default value of null when they are declared.


2) Can you explain the difference between the Stack and the Heap ?

The stack contains value data types on a first in, first out basis.
The heap contains reference data types.


3) Can you give some examples of Value data types ?

struct 
enum
System.Byte // unsigned integer 0 to 255
System.Decimal
System.Double
System.Single
System.Int16
System.Int32
System.Int64
System.DateTime
System.Windows.Forms.Point // structure
System.Drawing.Rectangle // structure
System.Drawing.Color // structure


4) Can you give some examples of Reference data types ?

class 
interface
System.String
System.Text.StringBuilder
System.Object
System.Delegate
System.Array
System.Tuple


5) What .NET data types do the following keywords map to ?

short - System.Int16 
int - System.Int32
long - System.Int64
float - System.Single
decimal - System.Decimal
double - System.Double
int[] - System.Int32[]


6) Can you identify the underlying .NET data type of a variable or object at run-time ?

Yes. The run-time data type can be found using the GetType method.
You cannot use the GetType method in conjunction with COM Interop.
The GetType method however will return "System._ComObject" for all COM Interop objects.

if (variable.GetType().FullName == "System.Int32" ) 


7) Can you identify the underlying COM Interop data type of a variable or object at run-time ?

Yes. The run-time data type can be found using either the 'is' operator or the 'as' operator.

if (myObject is Excel.Range) 

Excel.Range myRange = myObject as Excel.Range
if (myRange != null)


8) What is the 'typeof' Operator ?

This operator can be used at compile-time to return the System.Type object for a particular data type keyword.
This operator works with both value and reference data types.

System.Type MyType1 = typeof(System.Int32); 
System.Type MyType2 = typeof(int);

System.Int32 myInteger = 10;
System.String myString = "";
System.Array myArray = new int[] {1,2};

if (myInteger.GetType() == MyType1) ) { };
if (myString.GetType() == typeof(string) ) { };
if (myArray.GetType() == typeof(System.Array) ) { };


9) Is there any difference between the following lines of code ?

int myValueType = 20; 
MessageBox.Show(myValueType.GetType().Name) // Int32
MessageBox.Show(myValueType.GetType().FullName) // System.Int32
MessageBox.Show(myValueType.GetType().ToString()) // System.Int32


10) Is there any difference between the following lines of code ?

string[] myReferenceType = new string[] {"Mon", "Tue", "Wed"}; 
MessageBox.Show(myReferenceType.GetType().Name) // String
MessageBox.Show(myReferenceType.GetType().FullName) // System.String[]
MessageBox.Show(myReferenceType.GetType().ToString()) // System.String[]


11) What is a Literal Number Suffix ?

Also known as numeric literal suffixes.
In most cases the compiler is able to determine the correct data type for a numerical literal however there might be times when the default data type is different to the desired one.
In these cases a suffix can be added to explicitly tell the compiler which data type you want to use.

myNumber = 10000000F  // float = System.Single 
myNumber = 10000000U // uint = System.UInt32
myNumber = 10000000L // long = System.Int64
myNumber = 10000000UL // ulong = System.UInt64
myNumber = 10000000M // decimal = System.Decimal


12) What are Nullable data types ?

These are Value data types that can be assigned a null value.
This does not affect the default value.
They represent all the values of their underlying data type plus the additional null value.

int? myNumber = null; 
System.Nullable<int> myNumber = null;

Each instance of a nullable data type has two public read-only properties.
*) HasValue - returns true if the variable contains a non-null value.
*) Value - should only be accessed when HasValue is true.

int? myNumber = null; 
myNumber = 50
if (myNumber.HasValue == true)
{
   MessageBox.Show(myNumber.Value);
}


13) Can you explain the following lines of code ?

int? myNumber = null; 
long myReturn;
myReturn = myNumber ?? 20.5;

The nullable coalescing operator (??) can be used to provide an alternative value when a variable is null.
This operator works with both value and reference data types.

System.Array myArray; 
long myReturn;
myReturn = myArray ?? 20.5;

An array variable is declared with an initial default value of null.
A long variable is declared with an initial default value of zero.
The long variable is then assigned the value 20.5 because the myArray variable is null.


14) Can you explain the following lines of code ?

int myNumber = 10; 
myNumber += DateTime.Today.Day;
MessageBox.Show(myNumber);

An integer variable is declared and is assigned the value 10.
The addition self-assignment operator (+=) adds the numerical day of the month to the value 10.
This total is then displayed in a message box.


15) Can you convert a string data type to an integer data type ?

int myNumber = (int)myString; 
int myNumber = myString as int;
int myNumber = System.Convert.ToInt32(myString);


16) Can you convert an integer data type to a string data type ?

Yes. There are a numerous ways this can be done.

int i = 10; 
string s;
s = i.ToString();
s = System.Convert.ToString(i);
s = System.String.Format("{0}",i);
s = $"{i}";
s = "" + i;
s = System.String.Empty + i;
s = new System.Text.StringBuilder().Append(i).ToString();


17) What is arithmetic overflow and underflow ?

When you perform an integer arithmetic operation and the result goes outside the range of the data type.
To modify and control overflow/underflow there are two keywords you can use 'checked' and 'unchecked'.
In a checked context, arithmetic overflow raises an exception
In an unchecked context, arithmetic overflow is ignored and the result is truncated or wrapped.
By default non-constant expressions are not checked for overflow exception at run-time.
Code where unexpected wrapping arithmetic needs to be detected you should use checked context.
Code that relies on wrapping arithmetic should use unchecked context.

int myInt = 2147483647 + 10;              // generates a compile-time error 
int number = 10
int myInt2 = 2147483647 + number; // no compile time error or run time exception

checked
{
   int number = 10;
   int myInt2 = 2147483647 + number; // generates an overflow run-time exception
}


18) What is Casting ?

Casting is the name used to describe an explicit data type conversion.
This has nothing to do with boxing or unboxing.

long myLarger = 500000; 
int mySmaller;
mySmaller = (int)myLarger;


19) Can you describe Boxing and provide an example ?

Value data types can be converted to objects. This is called Boxing.
Boxing is encapsulating a copy of a value data type inside a System.Object.
When a value data type is boxed it is allocated on the heap and not on the stack.

int myNumber = 5; 
object MyObject1 = myNumber; // implicit boxing
object MyObject2 = (object)myNumber; // explicit boxing
object MyObject3 = myNumber as object; // explicit boxing

int myInt = 5;
System.Collections.ArrayList arrList = new System.Collections.ArrayList();
arrList.Add(myInt); // implicit boxing


20) Can you describe Unboxing and provide an example ?

System.Object data types can be converted into value data types. This is called Unboxing.

object myObject = 10;                              // implicit boxing 
int myNumber = (int)myObject; // explicit unboxing
int myNumber = myObject as int; // explicit unboxing
int myNumber = System.Convert.ToInt32(myObject); // explicit unboxing


21) What is the difference between a Literal constant and a Symbolic constant ?

A literal constant is a specific value such as a number, boolean, date, text.

bool myBoolean = false; 

A symbolic constant is a literal constant that is represented by a name.

public const string myText = "text"; 


22) Can you have a DateTime Literal constant in C# ?

C# does not support date or time literal constants (however VB.Net does).
A date and time literal constant must be declared using the System.DateTime class.

System.DateTime myDate = new System.DateTime(1900, 1, 1); 


23) Can you define a String constant that can be accessed anywhere ?

public class MyConstants 
{
   static const string MYTEXT = "hello";
}


24) What is an Enumeration ?

An Enumeration provides a way of grouping symbolic constants.
The default data type is System.Int32.
The first item in an enumeration has a value of 0.
An enumeration is a value data type.
It is possible to convert integer values to their corresponding enumeration data types.
The default access modifier for an enumeration is public.

public enum enMyCities 
{
    london = 1,
    tokyo = 2
}


25) Is it possible to return the string names instead of the numbers from an Enumeration ?

Yes. You can use the enumeration GetName method.

int myValue = enMyCities.tokyo; 
string MyText = System.Enum.GetName(typeof(enMyCities), myValue);


26) Write code to iterate through the values defined in an Enumeration ?

The Enum base class does not support the IEnumerable interface.
However you can use the GetValues method which returns all the enumerated values in an array.

foreach (enMyCities city in Enum.GetValues(typeof(enMyCities))) 
{
    Console.WriteLine( {0} - ( {1} ), city, (int)city);
}


27) What is an Immutable data type ?

This is a type of object whose value or state cannot be changed after it has been created.
The System.String is an immutable data type.
Every time the value is modified a new instance is created.

System.String myText = "some text"; 
myText = myText.Replace("e","a");


28) What is the difference between System.String and System.Text.StringBuilder ?

System.Text.StringBuilder is mutable and is more efficient when a lot of string manipulations are required.
System.String is immutable.

System.Text.StringBuilder myStringBuilder; 
myStringBuilder = new System.Text.StringBuilder("some text");
myStringBuilder.Append("more");
myStringBuilder.Replace("e","a");


29) Describe the 'System.Tuple' data type ?

This is a data structure that has a specific number of elements and a sequence.
This data type directly supports up to seven elements.
This is a reference data type.

System.Tuple <int, string, bool> MyTuple; 
MyTuple = new System.Tuple<int, string, bool>(0, "text", false);


30) What does Strongly Typed mean ?

A programming language is strongly typed if there are no implicit type conversions.
A strongly-typed programming language is one in which each data type is predefined as part of the programming language and all constants or variables must be defined with a specifc data type.
An advantage of strong data typing is that it imposes a rigorous set of rules on the programmer and therefore guarantees a certain consistency of results.


31) Is C# a Strongly Typed programming language ?

Yes. C# and VB.Net are both strongly typed languages.


32) What is the difference between Procedural and Object Orientated programming ?

Procedural is based in a modular approach where a larger program is broken up into smaller procedures or functions.
Each procedure has a set of instructions that is executed one after another.
Access modifiers are not used in procedural programming which means that most of the code can be accessed from anywhere.


33) Is an Array a value data type or a reference data type ?

All arrays are reference data types.
They are implicitly derived from System.Array which is derived from System.Object.

string[] myArray = new string["Mon","Tue","Wed"]; 
MessageBox.Show(myArray.GetType().FullName); // System.String[]


34) What is the difference between an Array and a Collection ?

Arrays are strongly typed collections of the same data type that have a fixed length that cannot change at run-time.
Collections are not strongly typed and can store different data types which are dynamic in size.


35) Can you give some examples of different types of Collections ?

System.Collections.ArrayList 
System.Collections.Generic.List
System.Collections.Generic.Dictionary
System.Collections.Generic.KeyValuePair


36) Can you create a list containing the values 1,2,3 using a generic collection class ?

System.Collections.Generic.List<int>MyList1; 
MyList1 = new System.Collections.Generics.List<int>();
MyList1.Add(1);
MyList1.Add(2);
MyList1.Add(3);

System.Collections.Generic.List<int>MyList2;
MyList2 = new System.Collections.Generics.List<int> {1, 2, 3};


37) How would you return the size of a 1 dimensional array ?

This array is a zero based array.

int[] myArray = new int[3];                  // initialised to default values 
int[] myArray = new int[3] {1, 2, 3};
int[] myArray = new int[] {1, 2, 3};
int[] myArray = {1, 2, 3};
var myArray = new[] {1, 2, 3}; // implicitly typed, inferred from items
System.Array myArray = System.Array.CreateInstance( typeof(System.Int32), 3 );

int arraySize = myArray.Length - 1; // the total items in the array
int arraySize = myArray.GetLength(0); // the size of a particular dimension
int arraySize = myArray.GetUpperBound(0); // the highest index in the array


38) How would you return the size of a 2 dimensional array ?

This array is a zero based array.

int[] myArray = new int[ , ] { {1, 2}, {3, 4}, {5,6} } 
int arraySize = myArray.GetLength(0);
int arraySize = myArray.GetUpperBound(0); // the highest index in the array


39) How would you determine the number of dimensions in an array ?

You can use the Rank property.

int dimensionSize = myArray.Rank; 


40) Can you create arrays that are not zero-based ?

Yes. This creates a 2 dimensional array

1 dimensional array, non zero based 
??

For multidimensional arrays Array.CreateInstance can be used to create non-zero index based arrays

2 dimensional array, non zero based 
int[ , ] myArray = (int[ , ]) System.Array.CreateInstance(typeof(int), new int[] { 2,2 }, new int[] { 100,100 });
??


41) How would you return the size of a 2 dimensional array that is not zero based?

This array is not a zero based array.

int[] myArray = new int[ , ] { {1, 2}, {3, 4}, {5,6} } 
int arraySize = myArray.GetLength(0);
int arraySize = myArray.GetUpperBound(0); // the highest index in the array


42) What is the fastest way to add up all the numbers in an array ?

Yes. Using LINQ.

int myArray = new int[] { 1, 1, 1, 1, 1, 1, 1 } 
int myTotal = myArray.Sum();
// pre .NET 3.5 - using a delegate
Array.ForEach(MyArray, delegate(int i) { myTotal += I; } );


43) What is the difference between a Rectangular Array and a Jagged Array ?

A rectangular array has the same dimensions and sizes.

string[, , ,] myArray; 

A jagged array can have different dimensions and sizes. Also called an array of arrays.

string[][][] myArray; 


44) What is the difference between a deep copy and a shallow copy ?

*) Deep Copy - copies across both Value data types and Reference data types.
Reference data types are copied across in their entirety as new objects. A different but identical object.
*) Shallow Copy - copies across both Value data types and Reference data types.
Reference data types are not copied across and will be pointing to the same objects.


45) What is the difference between System.Array.CopyTo and System.Array.Clone

Both perform a shallow copy.

System.Array.CopyTo    // copies items into an existing array. This is more flexible 
System.Array.Clone // returns a new array with all the same items.


46) Write a For loop to display the values in a list ?

System.Collections.Generic.List<int>MyList; 
for (int count = 0; I < MyList.Length; i++)
{
    MessageBox.Show(MyList[count]);
}


47) Write a For-Each loop to display the values in a list ?

foreach (int myNumber in MyList) 
{
    MessageBox.Show(myNumber);
}


48) Write a method to return the length of a generic list without using the Count method or a For loop ?

int ListCount(System.Collections.Generic.List MyList) 
{
   int itotal = 0;
   while (MyList.ElementAtOrDefault(itotal) != null)
   {
      itotal += 1;
    }
    return itotal;
}


49) What is the difference between 'break' and 'continue' inside a for loop ?

Break - breaks out of the loop completely
Contine - continues to execute the next iteration


50) Write a Switch statement to match against two conditions ?

switch (myText) 
{
   case "one":
      break;
   case "two":
      break;
   default:
      break;
}


51) Can you describe the purpose of a Try-Catch-Finally block ?

The try block encloses those statements that might cause an exception.
The catch block can handle exceptions.
The finally block always executes and contains any cleanup code.

try 
{ }
catch
{ }
finally
{ }


52) Can you have a Try block with no Catch block or Finally block ?

No. A Try block must be followed by either a Catch block, a Finally block or both.


53) Can multiple Catch blocks be executed ?

No. When an exception occurs the correct catch block is executed and then control is passed to the finally block.


54) What happens if the exception is not matched by a Catch block ?

The exception will be treated as unhandled and will propogate up the call stack.


55) When does the Finally block get executed ?

It always gets executed even if an exception occurs.


56) Can you put a return statement inside a Finally block ?

No.


57) What would the syntax be to catch any possible type of Exception ?

Catch 
Catch (System.Exception)
Catch (System.Exception ex)


58) Can you define your own User Defined Exceptions ?

Yes. You can derive from the System.Exception class.
Never use the System.ApplicationException class.

class UserNameInvalidException : System.Exception 
{
   class UserNameInvalidException(string MyMessage) : base (MyMessage)
   {}
}


59) Is there any difference between the following lines of code ?

try 
{ }
catch (System.Exception ex)
{
   throw;
   throw ex;
   throw new System.Exception("message",ex);
}

*) throw - will rethrow the original exception and preserve the stack trace.
*) throw ex - will rethrow the original exception but resets the stack trace.
*) throw new System.Exception - will create a brand new exception which resets the stack trace and loses the type of exception.


60) Can you give some examples of different types of Exceptions ?

ArgumentNullException - An argument that is passed to a method has a null value.
IndexOutOfRangeException - An index is outside the bounds of an array or collection.
StackOverflowException - An arithmetic, casting or conversion operation results in an overflow.
DivideByZeroException - The denominator in an Integer or Decimal division is zero.


61) What is Object Orientated programming ?

This is a style of programming that is based on objects containing methods and properties arranged in a hierarchy.
This type of programming is based around four key features:
Polymorphism - Create routines that can operate on objects of different types. This is handled by late binding and multiple interfaces.
Encapsulation - Hide parts of the implementation and hide complexity. This is achieved using access modifiers.
Inheritance (Interface) - (Public Inheritance) Define methods (without implementation) that must be declared in a derived class.
Inheritance (Implementation) - (Private Inheritance) Inherit method implementation from a base class.


62) Is C# an Object Orientated programming language ?

Yes. It has the four key features.


63) Can you describe the four different types of inheritance ?

Single Inheritance - contains one base class and one derived class.
Hierarchical Inheritance - contains one base class and multiple derived classes with the same base class.
Multi-level Inheritance - contains a class derived from another derived class.
Multiple Inheritance - (not supported in C#) contains a class derived from multiple base classes.


64) How would you describe the default Access Modifier ?

The default access modifier is the least restrictive based on the current scope.


65) Can you describe the five different levels of accessibility ?

public - everywhere
protected internal - inside the class and from any derived class in any assembly and from anywhere in that assembly (base classes)
internal - anywhere in that assembly
protected - inside the class and from any derived class in any assembly (base classes)
private - inside the class


66) What is an Interface ?

An interface is a contract that defines the signature for any object that is derived from it.
An interface can contain methods, properties, indexers and events.
An interface cannot contain constants, fields, instance constructors, types or static members.
Interfaces can be 'public', 'private', 'internal'.
The default access modifer for an interface is 'internal'.

internal interface MyInterface 
{
   void MyMethod(string MyText);
   string Property_Name { get; set; }
}


67) What type of Access Modifiers can you have on Interface members ?

None. You cannot use any explicit access modifiers.
Interface members are always 'public' by definition.


68) Can an Interface contain implementation ?

No. An interface can only contain the signature, it cannot contain any implementation.


69) Can an Interface implement from another Interface ?

Yes. An interface can inherit from one or more interfaces.
An interface cannot inherit from a Structure or Class.

interface MyInterface : BaseInterface1, BaseInterface2 
{ }


70) What is a Structure ?

A structure is the definition of an object, similar to a data record.
A structure cannot be inherited from.
A structure is a value data type.
A structure can contain implementation.
A structure cannot be declared static although it can have static members.
Structures can be 'public', 'private', 'internal'.
The default access modifier for a structure is 'internal'.

internal struct MyStructure 
{
   public string _TextField;
   internal void MyMethod();
   private string Property_Name { get; set: }
}

A structure can contain fields, methods, properties, enumerations, delegates, events, constructors, indexers, operator methods, classses.
A structure cannot contain finalizers or destructors.


71) What type of Access Modifiers can you have on Structure members ?

Structure members can be 'public', 'private', 'internal'.
Structure members cannot be 'protected internal' or 'protected' because they do not support inheritance.
The default access modifier for a structure member is 'private'.


72) What is the difference between a Structure and a Class ?

Structures are value types (stored on the stack), but classes are reference types (stored on the heap).
Structures do not support inheritance because you cannot have 'protected' or 'protected internal' access modifiers.
Structures cannot have destructors, but classes can.
Structures cannot initialise non static fields, but classes can.


73) What are the similarities between a Structure and a Class ?

Both can contain fields, methods, properties.
Both can inherit from interfaces.
Both can have 'public', 'private' and 'internal' access modifiers.
Both can contain implementation.


74) Can a Structure inherit from an Interface ?

Yes. Although the correct term is implement rather than inherit.
A structure can implement from one or more interfaces.
A structure cannot inherit from a Structure or Class.

struct MyStructure : MyInterface, MyInterface2 
{ }


75) Can a Structure contain a Class ?

Yes. Although this is not best practice.

struct MyStructure 
{
    public class MyClass
    {}
}


76) Can you have nested Structures ?

Yes. It is possible to declare a structure inside another structure.

struct MyStructure 
{
    public struct MyNestedStructure
    {}
}


77) Can a Structure contain a member variable that has a Structure data type.

Yes

struct MyStructure_B 
{
    private MyStructure_A myRecord;
}


78) Can a Structure contain 'static' fields ?

Yes. Static fields can be initialised inside a structure.

struct MyStructure 
{
    static string _TextField;
}


79) Can a Structure contain 'static' methods ?

Yes. They can be invoked by using the name of the structure.
Static members can only access other static members.


80) Describe the difference between passing a Structure to a method and passing a Class to a method ?

When a structure is passed by value "a copy" of the object is passed in.
When a class is passed by value the actual object is passed in.
When a structure is passed by reference the actual object is passed in.


81) Can a Structure have a Constructor ?

Yes but it will not be the default constructor.
It is possible to include a constructor but it must have at least one parameter.
Any private members can only be initialized in a constructor.
A default constructor (with no parameters) is created automatically and therefore one cannot be defined.
It is an error to initialize an instance field in a structure constructor.

internal struct MyStructure 
{
   private string _privateField;
   public string _textField;

   public MyStructure(string textValue)
   {
      _privateField = "somevalue";
      _textField = textValue;
   }
}


82) Write code to instantiate an instance of a Structure ?

You can create an instance of a Structure using the 'new' keyword.
The first line uses the default parameterless constructor.
The second line uses a custom constructor.

MyStructure struct1 = new MyStructure(); 
MyStructure struct2 = new MyStructure(10,20);


You can also create an instance by just declaring it (without using new).
The fields will remain unassigned and the object cannot be used until all the fields are initialised.

MyStructure struct3; 
struct3.Field1 = 10;
struct3.Field2 = 20;


83) What is a Class ?

A class is the definition of an object.
A class can contain fields, methods, properties, constructors, finalizer, destructor, indexers.
A class is a reference type.
Classes can be 'public', 'internal'
The default access modifier for a class is 'internal'.

internal class MyClass 
{ }


84) What type of Access Modifiers can you have on Class members.

Class members can be 'public', 'protected internal', 'internal', 'protected', 'private'.
The default access modifier for a class member is 'private'.


85) Can a Class inherit from a Interface ?

Yes. Although the correct term is implement rather than inherit.
A class can implement one or more interfaces.

class MyClass : MyInterface, MyInterface2, MyInterface3 
{ }

There must be Explicit Interface Implementation when you have two interfaces with the same methods.


86) Can a Class inherit from a Class ?

Yes. However you cannot inherit from multiple classes at the same time.

class MyDerived : MyClass 
{ }

You can however chain together classes that inherit off one another.

class MyClass_A 
{ }

class MyClass_B : MyClass_A
{ }

class MyClass_C : MyClass_B
{ }


87) Can a Class inherit from a Class and an Interface ?

Yes. Although to be precise the class inherits from a class and at the sam time can implement one or more interfaces.
The class must come first, followed by the interface(s).

class MyDerived : MyClass, MyInterface1, MyInterface2 
{ }


88) If you have an Internal Class should you make the members 'internal' or 'public' ?

A public member of an internal class is effectively internal because the class only has internal scope.
The members should be declared 'public' in case you want to change the class later to be public instead of internal.


89) Can you describe a situation when you need to have a 'public' method inside an Internal Class ?

Yes. This is necessary when an internal class implements an internal interface.
Interface members are always 'public' by definition and therefore the class must implement that member using a public access modifier.

internal interface MyInterface 
{
   void MyMethod()
}
internal class MyClass : MyInterface
{
   public void MyMethod()
   { }
}


90) What is a Nested Class ?

A nested class is a class declaration that occurs inside another class.
Nested classes can be 'public', 'protected internal', 'internal', 'protected', 'private'.
The default access modifier for a nested class is 'private'.

class MyClass 
{
   private class MyNested
   { }
}


91) What is a Class Method ?

A class method is a procedure or function that contains statements.

class MyClass 
{
   public void MyMethod()
   { }
   int MyMethod2()
   { }
}


92) What is the difference between 'ref' and 'out' parameters ?

ref - An argument passed as ref must be initialised before it is passed into a method.
out - An argument passed as out does not need to be initialised beforehand.

public void MyMethod(ref string myText1, 
                     out string myText2)
{ }


93) Can you describe Method Overloading ?

This is when you create another method with the same name but with a different signature.
The compiler determines which method to invoke at run-time.
There are three ways a method can be overloaded:
*) By changing the number of parameters.
*) By changing the order of the parameters.
*) By changing the data types of the parameters.


94) What is a Class Property ?

A property provides a way of exposing an internal data element inside a class.
You create a property by providing set and get property accessors.
The get accessor is used to return a value.
The set accessor is used to assign a new value.

class MyClass 
{
   private string _TextField;

   public string Property_Name
   {
      get { return _TextField; }
      set { _TextField = value; }
   }
}


95) What is an Auto Implemented Property ?

This provides a shorthand for the above by implicitly creating a private field.

public string Property_Name { get; set; } 


96) What does the 'abstract' modifier do ?

This can only be applied to methods and classes.
When applied to a method it creates an abstract method that HAS NO implementation.
An abstract method can only appear in an abstract class.


97) What is an Abstract Class ?

This class cannot be instantiated and can only be used as a base class.
Abstract classes can be 'public', 'internal'.
You must provide at least one abstract method in an abstract class.
They can provide implementation.

public abstract class MyAbstract 
{
   public abstract void MyMethod()
   internal abstract void MyMethod2()
   protected abstract void MyMethod3()
}


98) What type of Access Modifiers can you have on Abstract Class members ?

Abstract class members can be 'public', 'protected internal', 'internal','protected','private'.
The default access modifier for an abstract class method is 'public'.
An abstract method is by definition also a virtual method.


99) What is the difference between an Abstract Class and an Interface ?

An abstract class can have private and protected methods but an interface can only have public.
An interface only defines the methods (or signature) but an abstract class can provide code behind these methods.
Classes can implement multiple interfaces but can only implement one abstract class.
Any class can extend an abstract class. Only an interface can extend another interface.
Methods in an abstract class can be abstract or concrete. Methods in an interface are all abstract.
An abstract class can have a constructor. An interface cannot have a constructor.
A class extending an abstract class may or may not implement any of its methods. All methods of an interface have to be implemented when a class implements that interface.


100) Can you describe a situation when you need an 'internal' method inside an abstract class ?

If you want to prevent external inheritance while retaining visibility.


101) What is the difference between a Base Class and a Derived Class ?

A base class is a class declaration that is used as a basis for a second derived class.
If you want to extend the functionality or customise the functionality of an existing class you can derive another class from it.
A derived class inherits both structure and behaviour.


102) What does the 'static' modifier do ?

This can be applied to classes and methods.
It means you can call this method without instantiating the object.
A static class can only contain static members.
You cannot have a virtual static member.

static class MyClass 
{
   static void MyMethod()
}


103) Can a Class inherit from a Static Class ?

No.


104) What does the 'virtual' modifier do ?

This is applied to methods.
It means you HAVE THE OPTION TO override this method in a derived class.
You cannot have a private virtual method.

class MyClass 
{
   public virtual void MyMethod()
   {
      MessageBox.Show("MyClass - MyMethod");
   }
}


105) What does the 'override' modifier do ?

It means you have REPLACED the method in the derived class.
This changes the behaviour of the derived class.
You can override virtual methods in a normal class.
You can override abstract methods in an abstract class.
The method signature must be identical.

class MyClass 
{
   virtual void MyMethod()
   { MessageBox.Show("MyClass - MyMethod"); }
}

class MyDerived : MyClass
{
   override void MyMethod()
   { MessageBox.Show("MyDerived - MyMethod"); }
}

or

abstract class MyAbstractClass 
{
   abstract void MyMethod()
   { MessageBox.Show("MyAbstractClass - MyMethod"); }
}

class MyDerived : MyAbstractClass
{
   override void MyMethod()
   { MessageBox.Show("MyDerived - MyMethod"); }
}


106) What is displayed when this code runs ?

Both methods return MyDerived because this method has been overridden.

MyClass a = new MyDerived(); 
MyDerived b = new MyDerived();
a.MyMethod(); // MyDerived - MyMethod
b.MyMethod(); // MyDerived - MyMethod


107) What does the 'new' modifier do ?

This can only be applied to methods.
It means you have CREATED a method with the same name in a derived class.
This is the DEFAULT when your derived class has members with the same name as the base class.

class MyClass 
{
   virtual void MyMethod()
   { MessageBox.Show("MyClass - MyMethod"); }
}
class MyDerived : MyClass
{
   new void MyMethod()
   { MessageBox.Show("MyDerived - MyMethod"); }
}


108) What is displayed when this code runs ?

MyClass a = new MyDerived(); 
MyDerived b = new MyDerived();
a.MyMethod(); // MyClass - MyMethod
b.MyMethod(); // MyDerived - MyMethod


109) What is the difference between the 'new' modifier and the 'override' modifier ?

The 'override' modifier will create a different method in the derived class.
The 'new' modifier will replace the base class member.


110) What does the 'sealed' modifier do ?

This is applied to classes and methods.
It means you cannot override the base class method.
A sealed class cannot be inherited from.
A sealed method cannot be overridden in a derived class.

class MyClass 
{
   sealed void MyMethod()
}


111) What does the 'volatile' modifier do ?

It means that its value can be changed by another thread.
This modifier tells the compiler that this field could be accessed on multiple threads.
When the code is compiled, the compiler will make various optimisations on the assumption that variables will only be accessed by one thread at a time.
Using this modifier ensures that one thread retrieves the most up-to-date value written by another thread.
Writing non-blocking or lock free multithreaded code is very complicated.

class MyClass 
{
   volatile void MyMethod()
}


112) What does the 'readonly' modifier do and how is different to 'const' ?

This is a modifier that can be used on fields.
Therefore readonly fields can have different values depending on the constructor used.

class MyClass 
{
   public readonly int _NumberField = 5;
}


113) What is the difference between the 'readonly' modifier and the 'const' modifier ?

A 'readonly' variable can be initialised at run-time or in the class's constructor.
A 'constant' variable must be initialised at compile-time in the declaration.


114) What is a Constructor ?

A constructor is a member function in a class that has the same name as the class.
This method is automatically invoked when an object is created.
It can be used to initialise the class members.
They can be overloaded.
They do not return a value.
Having a class constructor is optional.

class MyClass 
{
   void MyClass() // constructor
   { }
}


115) Can you overload the default Constructor ?

Yes. You can leave the parameterless one as well if you want to.

class MyClass 
{
   void MyClass(string myText) // constructor
   { }
}


116) Can you describe when you would use a Private Constructor ?

Private constructors are used to prevent creating instances of a class that have no instance fields or methods.
It ensures the object can only be created by a member of the class.

class MyClass 
{
   private MyClass() // constructor
   { }
}


117) Can a Class have a Static Constructor ?

Yes. A non static class can have a static constructor. It can be used to initialize static data.
It is called automatically before any static members are referenced.
It is called automatically before the first instance is created.

class MyClass 
{
   static MyClass() // constructor
   {
   }
}


118) What is the 'base' keyword used for ?

The base keyword is used to access members of the base class from within a derived class.
The base class can only be accessed in a constructor, an instance method or an instance property accessor.
If the derived class overrides a base class method then the base keyword can be used to call the base class method.
You can also use the base keyword to specify which base class constructor should be called on the derived class constructor.


119) Is it possible for a class to inherit the constructor of its base class ?

No.


120) If a base class has an overloaded constructor and a derived class also has an overloaded constructor how can you call the base class constructor ?

public class MyClass 
{
   public MyClass(string MyText) // constructor
   {
   }
}
public class MyDerived : MyClass
{
   public MyDerived(string MyText, int myValue) : base(MyText)
   {
   }
}


121) What is a Destructor ?

A destructor implicitly calls the System.Object.Finalize method on the base class of the object.
A destructor cannot be called, it is invoked automatically.

public class MyClass 
{
   ~MyClass()
   {}
}

This is equivalent to the following:

public class MyClass 
{
   protected override void Finalize()
   {
      base.Finalize();
   }
}


122) What is a Finalizer ?

The word Finalizer refers to the System.Object.Finalize method.
Managed memory which is allocated using the new operator does not need to be explicitly released because it is released by the garbage collection process automatically.
This method can be used to clean up and destroy any unmanaged memory resources.
However there are two shortcomings with this method:
*) This method (if it runs at all) is called at some undetermined time in the future which means the resource is not cleaned up immediately.
*) This method executes on a different thread and therefore the memory is not actually released until the automatic garbage collection runs again.


123) Can you describe the Dispose Pattern ?

This pattern provides a standard convention for working around the shortcomings of the Finalize method.
This pattern uses the System.IDisposable interface.

public class MyObject : System.IDisposable 
{
   bool _disposed;

   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }

   protected virtual void Dispose(bool disposeOfManaged)
   {
      if (this._disposed == false)
      {
         if (disposeOfManaged == true)
         {
            //code to clean up managed resources
            component.Dispose();
         }

         //code to clean up unmanaged resources

         this._disposed = true;
      }
   }

   protected override void Finalize()
   {
      Dispose(false);
   }
}


124) Can you describe how Garbage Collection works ?

The garbage collector automatically gets information about unreferenced objects from the .NET runtime environment and then invokes their Finalize method.

GC.Collect 


125) Can you explain what an iterator is as well as an iterator block ?



126) Can you describe the IEnumerable interface ?

This interface enables you to use the foreach loop and for loop statements.
All the standard collection classes and the generic collection classes all implement this interface.

System.Collections.Generic.List MyList; 
MyList = new System.Collections.Generic.List { "one", "two", "three", "four" };
foreach (string mytext in MyList)
{
    Console.WriteLine(mytext);
}


127) What methods does the IEnumerable interface have ?

GetEnumerator -
This interface requires that you also implement the IEnumerator interface.


128) Can you describe the IEnumerator interface ?

This interface supports a very simple iteration.


129) What methods and properties does the IEnumerator interface have ?

M - MoveNext - advanced to the next element
M - Reset - moves to the initial position which is before the first element.
M - Dispose
P - Current - returns the object at the current location


130) Which of these interfaces inherit from the IDisposable interface ?

IEnumerator - (Added in C# 1.0) doesn't inherit
IEnumerator&lgT> - (Added in C# 2.0) does inherit
IEnumerable&lgT> - (Added in C# 2.0) does inherit


131) Can you describe and give an example of using the yield keyword ?

??


132) Write your own collection that implements the IEnumerable interface

class MyCustomArray : IEnumerable, IEnumerator 
{
   object[] m_Items = null;
   int m_index = 0;

   public MyCustomArray()
   {
      m_Items = new object[50];
   }
   public void Add (object item)
   {
       m_Items[m_index] = item;
       m_index ++;
   }
   public IEnumerator GetEnumerator()
   {
       foreach (object obj in m_Items)
       {
            if (obj == null) { break; }
            yield return obj;
       }
   }
   public bool MoveNext()
   public void Reset()
   public object Current { get{} }


133) What is a Delegate ?

A delegate represents a reference to a method that has a particular signature (parameter list and return type).
Delegates give you a way of calling a method at run-time.
When you instantiate a delegate you can associate its instance with any method with a matching signature.
Delegates are used to pass methods as arguments to other methods.

public delegate int MyDelegate(int x); 

Examples include: type safe functions, pointers, callbacks.


134) Delegates with Named Methods

When you instantiate a delegate by using a named method, the method is passed as the parameter.

delegate int MyDelegate(int x); 
void DoSomething(int a)
{ return a * a; }
MyDelegate del = DoSomething;


135) Delegates with Anonymous Methods

Introduced in C# 2.0 (.NET 2.0).
An anonymous method provides a way of passing a block of code as an argument instead of creating an explicit method.

delegate int MyDelegate (int x); 
MyDelegate del = delegate (int a)
   { return a * a; }


136) What is a Lambda Expression ?

Introduced in C# 3.0 (.NET 3.5).
A lambda expression is a more concise way of writing an anonymous function.
You specify the input parameters (if any) on the left of the lambda operator => and the statement block (or expression) on the right.

delegate int MyDelegate (int x); 
MyDelegate del = a => a * a;

These are often used to create delegates for use in LINQ queries.


137) What is the difference between a Delegate and an Event ?

An event is something that can be added or removed from an object.
When you add or create an event you are storing a delegate reference which can then be called at run-time.


138) What is an Event ?

An event is an indication that a state is about to change or that a state has changed.
An event handler is a method that is invoked using a delegate.

button.click += delegate(System.Object o, _ 
                         System.EventArgs e)
                        { MessageBox.Show("pressed"); };

139) What is a Multicast Delegate ?

A Delegate object holds a reference to a single method.
It is possible for a delegate object to hold references to multiple methods.
These delegates are called multicast or combinable delegates.


140) What is a Generic Delegate ?

A generic delegate is ??
There are three types:
Action - can include 0 to 16 input parameters, no return type
??
Func - can include 0 to 16 input parameters and one return type

System.Func MyDelegate = MyMethod; 
public static string MyMethod(string inputstring)
{ return ""; }

Predicate - can verify a certain criteria and return a boolean value


141) Can you describe some situations when you would use Delegates ?

Callback Mechanism -
Asynchronous Processing -
Multi-Casting -
Abstract and Encapsulate Methods -


142) What is Multi-Threading ?

This allows different tasks to be carried out in parallel.
The advantage of a divide and conquer strategy is that it will improve performance.


143) What is the difference between a Background Thread and a Foreground Thread ?

A foreground thread runs indefinitely.
A background thread terminates when the foreground thread is stopped.


144) What does the 'async' keyword do ?

Introduced in C# 5.0 (.NET 4.5).


145) What is displayed when this code runs ?

public main() 
{
   Method1()
   MessageBox.Show("Two");
}

public async void Method1()
{
   thread.wait(10);
   MessageBox.Show("One");
}

The Method1 is executed on a different thread and this message box will only be displayed after the 10 seconds.
"Two"
"One"


146) What does the [ThreadStatic] attribute do ?

System.ThreadStaticAttribute 

This is used to indicate a variable is thread safe.
A static variable is not shared between threads.
Each executing thread will have a separate instance of the field and will independently set and get values for that variables.
If the variable is accessed on a different thread, it will contain a different value.


147) What is Reflection ?

This is a technique that allows you to fetch type (assembly) information at runtime programmatically. You can also achieve late binding using Reflection.
This allows you to examine or modify the meta data from assemblies at runtime.
This is useful for:
Viewing metadata -
Type discovery - examine the types in other assemblies
Late binding - based on Type discovery
Creating new types at runtime (Reflection Emit) Creating custom classes at runtime which will run significantly faster than a more generic class created at compile time


Reflection can be used to adapt a program execution at run-time
This is the process by which a program can read its own meta-data
A program is said to reflect on itself extracting metadata from its assembly and using that metadata to either inform the user or modify its behaviour


148) If you pass an object into a method and you want to find out what type it is - how can you do this ?

Declare the members you need in a class or interface and cast to that using Reflection.

public static T Cast<T>(object obj) 
{
   return (T)obj;
}

This method can then be invoked using Reflection.

methodInfo castMethod = this.GetType().GetMethod("Cast").MakeGenericMethod(t) : 
object castedobject = castmethod.Invoke(null, new object[] {obj});


149) What is ADO.NET ?

This provides a consistent way to access different types of data sources and different types of databases.


150) Can you describe the DataReader class in ADO.NET ?

The DataReader is a forward only approach to getting read-only data.
This will retain an open connection to the database while retrieving data.


151) Can you describe a DataSet in ADO.NET ?

The DataSet is a disconnected cache of data that allows you to create multiple tables and fill them with data from different sources.
A DataSet object is more inline with a VBA ADO recordset.
A DataSet can be used with no database and could be populated with data from an XML file or other source.
It also allows you to enforce relationships between the tables.
DataSets can be either Typed or UnTyped.
DataSets can be serialized.


152) What is the difference between the 'System.Data.SQLClient' namespace and the 'System.Data.OleDbClient' namespace ?

OleDbClient - This is a general data provider for targetting any OLE DB data source, including Access.
SQLClient - This is a specific data provider for targetting SQL Server databases.


153) Write the code to connect to the Northwind Access database using OleDbClient and execute a SQL statement.

??


154) What is the pre-requisite for connection pooling ?

??


Other ?

155) What is a HashTable ?

A hash table is a data structure that implements the IDictionary interface.
Is an example of a collection.
It is used to store multiple items and each one is associated with a unique key.
A hash table is an object that holds key-value pairs.


156) What is Serialisation ?

Converting an object into a stream of bytes is called serialisation.
This is useful when we want to transport, save or pass an object around.
For an object to be serialized it needs to inherit the ISerialize interface.
De-serialization is the reverse process of creating an object from a stream of bytes.


157) What do the [Serializable] and [NonSerializable] attributes do ?

System.SerializableAttribute 
System.NonSerializableAttribute

[Serializable()]
public class MyClass

This can be applied to classes and methods.
Used to indicate that a class or method can be serialized.


158) What is the 'using' statement ?

The using block is used to obtain a resource and use it and then automatically dispose of it at the end of the block.
This allows you to not specify the data type at declaration ?


159) Can you describe the concept of Generics ?

Generics provide type-safety to your class at compile-time


160) What do SOAP and REST stand for ?

SOAP = Simple Object Access Protocol
REST = REpresentational State Transfer


161) What are the differences between SOAP and REST ?

SOAP - describes itself using a wsdl (web description language) and has a defined contract
REST - lightweight http protocol that can return different formats (text, html, xml)


162) How can you return an error from a SOAP Web Service ?

Make sure the exception raised is derived from the SOAPException class.


163) Write a function that takes a date and returns the quarter that the date is in ?

public static int GetQuarter(System.DateTime myDateTime) 
{
   return System.Convert.ToInt32(System.Math.Ceiling(myDateTime.Month(3D));
}

The "D" literal number suffix tells the compiler that the literal value passed to the Month method is of data type double.
You can use this when you want an integer number to be treated as a double.


164) LINQ Question

.FirstOrDefault 


165) Write code that will resize a System.Drawing.Rectangle by reducing its height and width by 5 points ?

System.Drawing.Rectangle myRectangle = new System.Drawing.Rectangle(100,100); 
myRectangle.Inflate(-5,-5);


166) What is well formed XML ?

XML containing descriptive markup tags where all the tags are correctly formed and follow certain rules
Must contain at least one element
Must contain a unique opening and closing tag
All tags must be nested correctly
Xml tags are case sensitive
Attribute values must always be enclosed in double quotes.


167) What is XSLT ?

This stands for XML Stylesheet Language Transformations and is an xml based document used for transforming one type of XML into another type of XML.


168) What is a COM add-in ?

This Is a type of add-in that can be used to provide additional application-level functionality
A COM add-in implements the IDTExtensibility2 interface
It has been possible to create these since Visual Studio 2002.


169) What is a VSTO add-in ?

This is a type of add-in that can be used to provide additional application-level functionality
A VSTO add-in implements the IStartup interface (which is implemented in the Addins class/interface)
This interface is strongly typed and does not rely on late binding.
It has only been possible to create these since Visual Studio 2005.


170) What is ClickOne ?

ClickOnce is a deployment technology that allows you to create self-updating Windows-based applications that can be installed and run with minimal user interaction.
The core ClickOnce deployment architecture is based on two XML manifest files: a deployment manifest and an application manifest.


171) What is a Deployment Manifest ?

This is a file with the extension (.deploy) but in the context of VSTO this extension is (.vsto).
They are standard clickonce manifests but have a different file extension to enable the VSTO runtime to handle the file).
This file identifies which version of the application is currently deployed and also contains other useful deployment information.
There is only one deployment manifest per customisation and it references the application manifest.


172) What is an Application Manifest ?

This is a file with the extension (.manifest).
This file describes all the assemblies, dependencies, permissions etc.
And there is one file for each version of the customisation.


173) Can you describe Ribbon Customisation ?

Allows you to add (or replace) functionality to existing tabs, create new tabs, groups and commands
This can be done in two ways:
*) Using the CustomUI Editor to embed XML markup into the open xml format.
*) Using Visual Studio using to create a VSTO or COM add-in.


174) What is an Assembly ?

In .NET an assembly is a partially compiled code library used in deployment.
There are two types: process assemblies (exe) and library asemblies (dll).


175) What is an Application Domain ?

An application domain provides a flexible and secure method of isolating running .NET applications.
Before a .NET assembly can be executed it must be loaded into an application domain.
Errors in one application domain cannot affect code running in any other application domains.


176) What is a Namespace ?

A namespace provides a way of organising and grouping your classes.


177) What is Unit Testing ?



178) Can you give some examples of different types of test cases ?

Positive test cases - correct data, correct output
Negatve test cases - incorrect / missing / invalid data, proper handling
Exception test cases - exceptions are thrown and handled properly



© 2017 Better Solutions Limited. All Rights Reserved. © 2017 Better Solutions Limited

Prev