C# Test - Types

.C# Type Test


1. Name two constructs that are commonly used to create custom types. Explain how they are commonly used and how they differ.
Answer


2. Generally a class should be a first consideration before using a struct. List the four characteristics a type should have to be defined as a struct. Note: the type must contain all four of these characteristics.
Answer


3. What is printed from the following program?

namespace TypeTests
{
    struct TheStruct
    {
        private int field;
        public TheStruct(int value)
        {
            field = value;
        }
    }
    class TheClass
    {
        private int field;
        public TheClass(int value)
        {
            field = value;
        }
    }

    class Program
    {
        static void Main()
        {
            TheStruct s1 = new TheStruct(5);
            TheStruct s2 = new TheStruct(5);
            System.Console.WriteLine(s1.Equals(s2));

            TheClass c1 = new TheClass(5);
            TheClass c2 = new TheClass(5);
            System.Console.WriteLine(c1.Equals(c2));
        }
    }
}

Answer


4. What are the similarities and differences between "properties" and "fields"?
Answer


5. Code a program that contains a struct called "Rectangle". The struct should contain both a Height and WIdth property coded with a backing store. Use the struct to create a Rectangle type with the Height of 3 and a Width of 4. Then print out the Height and WIdth of the rectangle.
Answer


6. Change the "Rectangle" struct program coded in #5 above to have auto-implemented properties.
Answer


7.Change the "Rectangle" struct program coded in #6 above to have an object initializer to set the value of the properties.
Answer


8. Change the "Rectangle" struct program coded in #7 above to have a method called "MakeBigger" which will double the Height and Width of the rectangle.
Answer


9. Change the "Rectangle" struct program coded in #8 above to have the following:

A. Inside the struct, code a string array of three colors (Red, Green, Blue). As rectangles are created they should be of the next color in the array (R,G,B,R,G,B,...).
B. Code a getter method to return the current color.
C. Code a method to draw a rectangle on the console to the dimensions specified when creating the rectangle. Print a message beside each rectangle indicating the sized dimensions and the color.
D. Create four rectangles and verify they are drawn correctly. Verify the colors wrap back to the beginning of the color array.

.Rectangle Structure

Answer


10. List and define two access modifiers which can be used for class and struct types declared directly within a namespace (i.e. not nested within other classes or structs). Which one is the default access modifier?
Answer


11. List and define five access modifiers which can be used for nested types or for members?
Answer


12. Name two of the five access modifiers that are available for nested class types which are not available for nested struct types. Explain why those two access modifier are not available for struct types?
Answer


13. What is the default access level for the following types:

A. class (nested)
B. class (not nested)
C. struct (nested)
D. struct (not nested)
E. enum
F. interface

Answer


14. Which of the following types do not allow you to declare accessibility levels.

A. class
B. struct
C. enum
D. interface

Answer


15. Besides the access modifiers, list and explain 5 other modifiers for the class type:
Answer


16. Besides the access modifiers, list and explain 8 other modifiers for methods:
Answer


17. Besides the access modifiers, list and explain 4 other modifiers for fields:
Answer


18. Define an abstract class that stores two integer values. Include an abstract method which returns an integer value. Then derive two classes from the abstract class. Implement the abstract method in the derived classes, so that each class has an overridden method which returns a different mathematical operation on the two integers values.

Answer


19. Answer true or false to the following statements:

A. A namespace can directly contain fields and methods.
B. Abstract methods are only permitted inside abstract types.
C. An abstract method is implicitly also a virtual method.
D. It is possible to split the definition of a class or a struct, an interface or a method over two or more source files.

Answer


20. Answer true or false to the following statements about partial methods

A. A partial method can only be declared within a partial class or partial struct.

B. A partial method can split the implementation of a method.

C. A partial method can return a value.

D. A partial method can have an access modifier of "public".

E. A partial method must always have an implementation.

F. A partial method can have "ref" and "out" parameters.

G. A partial method can be static or generic.

H. You can make a delegate to a partial method that has been defined and implemented.

Answer


21. If a member is nested within another type, what two factors determine its accessibility?

Answer


22. In the following program, which statements will not compile because the variable is "inaccessible due to its protection level"?

namespace accessdomain
{   
    public class Outer
    {
        public static int publicInt;
        internal static int internalInt;
        private static int privateInt = 0;

        static Outer()
        {
            // Outer class can access public or internal members
            // in a public, private, or internal nested class
            Inner1.publicInt = 1;
            Inner1.internalInt = 2;
            Inner2.publicInt = 3;
            Inner2.internalInt = 4;
        }

        public class Inner1
        {
            public static int publicInt;
            internal static int internalInt;
            private static int privateInt = 0;
        }

        private class Inner2
        {
            public static int publicInt = 0;
            internal static int internalInt = 0;
            private static int privateInt = 0;
        }
    }

    class MainClass
    {
        static void Main()
        {
            Outer.publicInt = 1; // A.
            Outer.internalInt = 2; // B.
            Outer.privateInt = 3; // C.

            Outer.Inner1.publicInt = 1; // D.
            Outer.Inner1.internalInt = 2; // E.
            Outer.Inner1.privateInt = 3; // F.

            Outer.Inner2.publicInt = 1; // G.
            Outer.Inner2.internalInt = 2; // H.
            Outer.Inner2.privateInt = 3; // I.
        }
    }
}

Answer


23. Name the only two places where a "readyonly" field can be assigned a value.
Answer


24. Explain the difference between a "readonly" field and a "const" field.
Answer


25. Explain why the keyword "this" is not valid in a property, method, or field which has the "static" modifier?
Answer


26. What does global:: refer to?

Answer


27. In C#, what is the recommended way to create fields that have global scope (if you really must)?

Answer


28. Respond true or false to the following statements about constructors:

A. If you declare a constructor for a class that has no parameters, it may be referred to as the "default constructor". Additionally the constructor automatically created by the compiler when no constructor is defined is also referred to as the "default constructor".
B. structs cannot contain an explicit default constructor (i.e. constructor with no parameters)because one is provided automatically by the compiler.
C. You can chain constructors together by having one constructor call another.
D. An instance constructor is the same as a static constructor.
E. You will not be able to create an object if the corresponding class constructor has an access modifier of "private".
F. The compiler will attempt to create a constructor for a class if no constructor is declared.
G. You can access static members from a non-static (normal) constructor.
H. You can access non-static (normal) members from a static constructor.
I. Constructors can not have a return type.
J. Constructors can be overloaded. i.e. A class or struct may have multiple constructors that take different arguments.

Answer


29. Respond true or false to the following statements about enum types:

A. An enum can be directly define within a namespace (i.e. outside of a class or struct)? true - In fact they are usually declared directly in a namespace so they are available to all classes. This is not true of fields or methods however, they must be defined with a class or struct.
B. By default the first enumerator corresponds to value 1, and each successive enumerator is increased by 1. false - By default the first enumerator corresponds to value 0, and each successive enumerator is increased by 1.
C. Enumerators can use initializers to override the default values. true
D. Every enumeration must have an underlying integral type, with the default underlying type being an int. true
E. Which of the following are valid underlying integral types for enumerations (byte, sbyte, short, long, char). char is not a valid underlying type for enumerators.
F. You can explicitly assign some of the enum members without assigning values to others. true - The unassigned enum members keep incrementing from the last explicit value.
G. An enumerator can have white space in its name. false - An enumerator can not have white space in its name.
H. An explicit cast is required to convert the enum type to its underlying integral type. true - e.g. int x = (int) Days.Sunday;
I. The Enum methods GetName and GetValue return constant name and underlying value. - true
J. It is recommended that all Enum declarations should start with a zero value. - true. Use None=0 if you are going to start the enums at a non-zero value
K. You can add a member to an enumeration at run-time. - false. You cannot add an enumeration member at run-time.
L. Enum extension methods must be defined in a top level static class. They can not be in a nested or in non-static classes. - true
M. An extension method will never be called if it has the same signature as a method defined in a type. - true Instance methods have priority.
N. The attributes [Flags] and [FlagsAttribute] have the same meaning. yes - Flags is shorthand for FlagsAttributes. Flags enumerations are used for masking bit fields and doing bitwise comparisons (Must use powers of two for the bitwise comparisons to work).
O. The [FlagsAttribute] should only be used on an enumeration if a bitwise operation is to be performed on the enumeration value. - true

Answer


30. Name four traditional categories of polymorphism and their feature equivalent in C#.

Answer


31. Explain the difference between upcasting and downcasting. Code an example of upcasting and downcasting.

Answer


32. What happens when a cast fails when using the "as" operator?
Answer


33. Explain the special needs object-oriented languages have for polymorphism and give the definition of polymorphism usually associated with object-oriented languages.
Answer


34. C# calls it a base class, but what is it called in Java?
Answer


35. C# calls it a derived class, but what is it called in Java?
Answer


36. What feature is required in order for a programming to support polymorphism?
Answer


37. Choose which one of these methods is the most efficient method at casting reference types and explain why:
A. Perform a traditional cast and handle the 'InvalidCastException'.
B. Use the "is" operator to check for type compatibility before performing the cast.
C. Use the "as" operator and check the reference variable for null to see if the cast succeeded.
Answer


38. When polymorphism and inheritance are tightly linked because of static type checking, what component can be used to weaken the link and provide the class with more flexibility?
Answer


39. In NET 4.0 extension methods were introduced. What is the purpose of extension methods and how should they be declared?
Answer


40. How are indexers used? Write code to show how they are used.
Answer


41. What is the Law of Demeter (LoD)?
Answer


42. Write a method and a method call that uses both named and optional parameters.
Answer


43. What does the compiler do behind the scenes when a value type is declared as a nullable type? Code example usage of the null coalescing operator.
Answer


44. Code an example of constructor chaining.
Answer


45. Define the Big Ball of Mud principle.
Answer


46. What are the principles of SOLID in object-oriented design?
Answer


47. What must you do prior to a downcast in order for the downcast to be successful?
Answer


48. What is the purpose of an Interface?
Answer


49. How does an interface differ from a class?
Answer


50. Respond true or false to the following statements about interfaces

A. An interfaces can extend another interface.
B. The "is" operator can be used to determine if a class implements an interface.
C. An interface can be instantiated.
D. You can upcast and downcast with interfaces.
E. A class can implement only one interface.
F. A struct can implement an interface, but a struct can not inherit from a class.

Answer


51. Why is an abstract class like a cross between a class and an interface?

Answer


52. How are the following interfaces used:

A. IEnumerable and IEnumerator
B. IDisposable
C. IQueryable
D. INotifyPropertyChange
E. IComparable and IComparer
F. IEquatable and IEqualityComparer
G. IList
H. IDictionary
I. ICollection

Answer


53. Write code that illustrates the difference between an instance constructor and a static constructor.

Answer


54. What is the difference between the GetType() method and the typeof operator?

Answer


55. List the seven members all objects have.

Answer


56. Why are friend assemblies used?

Answer


57. What is "reimplementing an interface" and what problems can it cause?

Answer


58. What is the difference between generics and inheritance?

Answer


59. Compare and contrast Covariance and Contravariance as they apply to generics.

Answer


60. Explain generic constraints and provide a coding example.

Answer


61. What is the purpose of generics?

Answer


62. What are two purposes of the base keyword?

Answer


63. Explain boxing and unboxing.

Answer


64. Code an example of a class that implements more than one interface.

Answer


65. Explain what it means when they say: "inheritance is transitive".

Answer


66. Define encapsulation and explain how it is supported in C#.

Answer


67. Name the only two modifiers allowed for static constructors.
Answer


68. Define a delegate and list its uses.
Answer


69. Static Polymorphism is sometimes called Method __________ while Dynamic Polymorphism is called Method __________.
Answer


70.

Answer


71.

Answer


72.

Answer


73.

Answer


74.

Answer


75. Explain the difference between Lambda Expressions and Anonymous Methods.

Answer


76.

Answer


77.

Answer


78.

Answer


79.

Answer


80.

Answer


81.

Answer


82.

Answer


83.

Answer


84.

Answer


85.

Answer


86.

Answer


87.

Answer


88.

Answer


89.

Answer


90.

Answer


91.

Answer


92.

Answer


93.

Answer


94.

Answer


95.

Answer


96.

Answer


97.

Answer


98.

Answer


99.

Answer


100.

Answer


Answers


1. Answer is:
Two constructs commonly used to create custom types are:

A. class
B. struct

Both class and struct are used to create custom types by encapsulating a set of data and behaviors that belong together as a logical unit. In C# both class and struct can have: constants, fields, properties, indexers, methods, events, and static members.

A class is used to model more complex behavior, or contains data which is intended to be modified after the class object is created.
A struct is used for small data structures that primarily contain data which is not intended to be modified after the structure is created.

A class is reference type. When instantiated, a class variable holds a memory reference to the class data which resides in the heap.
A struct is value type. When instantiated, a struct variable holds the actual data which resides on the stack.

More differences:

  1. Struct can declare constructors, but they must have parameters. A default constructor (no parameters) is not allowed for a struct.
  2. Inheritance is not allowed with struct (other than from the base object class). Structs are inherently sealed.
  3. Both struct and class can use "new" operator to create an instance. However a struct can also be created without the "new" operator. When a struct is instantiated without the "new" operator, all the fields must be public and you must initialize all the fields yourself.
  4. Events declared in a class are automatically locked to make them thread safe. Events declared in a struct are not automatically locked.
  5. A class can contain volatile fields, while a struct can not.

Back


2. Answer is:
According to MSDN, a type should have all four of these characteristic to be defined using a struct:

  1. The type will have an instance size of 16 bytes or less.
  2. he type will be immutable.
  3. The type will logically represents a single value, similar to primitive types (int, double, etc.) Typical example of a struct is a point (x,y,z).
  4. The type will not have to be boxed frequently.

Back


3. Answer is:

namespace TypeTests
{
    struct TheStruct
    {
        private int field;
        public TheStruct(int value)
        {
            field = value;
        }
    }
    class TheClass
    {
        private int field;
        public TheClass(int value)
        {
            field = value;
        }
    }

    class Program
    {
        static void Main()
        {
            TheStruct s1 = new TheStruct(5);
            TheStruct s2 = new TheStruct(5);
            System.Console.WriteLine(s1.Equals(s2));  // Prints: True (Value type compare)

            TheClass c1 = new TheClass(5);
            TheClass c2 = new TheClass(5);
            System.Console.WriteLine(c1.Equals(c2));  // Prints: False (Reference type compare)
        }
    }
}

Back


4. Answer is:
The similarities and differences between "properties" and "fields" are:

"Fields" and "properties" are similar in that they are both used to store information in a class or a struct. However, a "field" is simply a public variable. While "properties" are methods which control how values are set and returned (through their get and set accessors). Typically "fields" are used for data that is protected or private, where "properties" are used to expose data to client code.

Back


5. Answer is:

namespace Rectangles
{
    struct Rectangle
    {
        // Height Property
        private int _height;
        public int Height
        {
            get { return _height; }
            set { _height = value; }
        }

        // Width Property
        private int _width;
        public int Width
        {
            get { return _width; }
            set { _width = value; }
        }
    }

    class Program
    {
        static void Main()
        {
            Rectangle myRectangle = new Rectangle();
            myRectangle.Height = 3;
            myRectangle.Width = 4;

            System.Console.WriteLine("Height is: {0} and width is: {1}", myRectangle.Height, myRectangle.Width);
        }
    }
}

Back


6. Answer is:

namespace Rectangles
{
    struct Rectangle
    {
        // Height Property Auto-Implemented
        public int Height { get; set; }

        // Width Property Auto-Implemented
        public int Width { get; set; }
    }

    class Program
    {
        static void Main()
        {
            Rectangle myRectangle = new Rectangle();
            myRectangle.Height = 3;
            myRectangle.Width = 4;

            System.Console.WriteLine("Height is: {0} and width is: {1}", myRectangle.Height, myRectangle.Width);
        }
    }
}

Back


7. Answer is:

namespace Rectangles
{
    struct Rectangle
    {
        // Height Property Auto-Implemented
        public int Height { get; set; }

        // Width Property Auto-Implemented
        public int Width { get; set; }
    }

    class Program
    {
        static void Main()
        {
            Rectangle myRectangle = new Rectangle { Height = 3, Width = 4 };  // With Object Initializer
            System.Console.WriteLine("Height is: {0} and width is: {1}", myRectangle.Height, myRectangle.Width);
        }
    }
}

Back


8. Answer is:

namespace Rectangles
{

    struct Rectangle
    {
        // Height Property Auto-Implemented
        public int Height { get; set; }

        // Width Property Auto-Implemented
        public int Width { get; set; }

        // Method to Increase Height and Width of Rectangle
        public void MakeBigger()
        {
            Height *= 2;
            Width *= 2;
        }
    }

    class Program
    {
        static void Main()
        {
            Rectangle myRectangle = new Rectangle { Height = 3, Width = 4 };  // With Object Initializer
            System.Console.WriteLine("Height is: {0} and width is: {1}", myRectangle.Height, myRectangle.Width);
            myRectangle.MakeBigger();
            System.Console.WriteLine("Height is: {0} and width is: {1}", myRectangle.Height, myRectangle.Width);
        }
    }
}

Back


9. Answer is:
Program with color array and draw method inside struct is shown below.

namespace Rectangles
{
    struct Rectangle
    {
        // Array of Colors
        static string[] color = "Red Green Blue".Split() ;
        static int colorIndex = 0;

        // Next Color Getter
        public string nextColor
        {
            get { return color[colorIndex]; }
        }

        // Width Property Auto-Implemented
        public int Width { get; set; }

        // Height Property Auto-Implemented
        public int Height { get; set; }

        // Method to Increase Height and Width of Rectangle
        public void MakeBigger()
        {
            Width *= 2;
            Height *= 2;
        }

        // Method to Draw Rectangle on Screen
        public void DrawRectangle()
        {
            System.Console.Write(' ');
            for (int i = 0; i < Width; i++)
                System.Console.Write('-');
            System.Console.WriteLine();

            for (int i = 0; i < Height; i++)
            {
                System.Console.Write('|');
                for (int j = 0; j < Width; j++)
                    System.Console.Write(' ');               
                if (i ==0)
                    System.Console.WriteLine("| This is a {0} x {1} rectangle in: {2}", Width, Height, nextColor);
                else
                    System.Console.WriteLine('|');
            }

            System.Console.Write(' ');
            for (int i = 0; i < Width; i++)
                System.Console.Write('-');
            System.Console.WriteLine();

            // Update color index
            if (colorIndex < 2)
                colorIndex++;
            else
                colorIndex = 0;
        }
    }

    class Program
    {
        static void Main()
        {
            // Create first rectangle, test MakeBigger method, print characteristics, draw on screen
            Rectangle myRectangle = new Rectangle { Width = 4, Height = 3};  // With Object Initializer
            System.Console.WriteLine("Width is: {0} and height is: {1}", myRectangle.Width, myRectangle.Height);
            myRectangle.MakeBigger();
            System.Console.WriteLine("Width is: {0} and height is: {1}", myRectangle.Width, myRectangle.Height);
            System.Console.WriteLine("The color of the next rectangle will be: {0}", myRectangle.nextColor);
            System.Console.WriteLine();
            myRectangle.DrawRectangle();

            // Create second rectangle in size specified using next color, draw on screen
            Rectangle myRectangle2 = new Rectangle { Width = 4, Height = 3 };           
            myRectangle2.DrawRectangle();

            // Create third rectangle in size specified using next color, draw on screen
            Rectangle myRectangle3 = new Rectangle { Width = 2, Height = 2 };
            myRectangle3.DrawRectangle();

            // Create fourth rectangle in size specified using next color, draw on screen
            Rectangle myRectangle4 = new Rectangle { Width = 1, Height = 1 };
            myRectangle4.DrawRectangle();
        }
    }
}

Back


10. Answer is:
public and internal are the only two valid access modifiers for class and struct types that are declared directly in a namespace. The default access modifier for them is internal. (i.e. private, protected, and protected internal access modifiers are not allowed for class and struct types that are declared directly in a namespace).

A. public - no access restrictions. Use when class, struct, or delegate needs to be available outside of assembly.
B. internal - access is limited to the current assembly. (default).

Back


11. Answers are:

A. public - no access restrictions. The most permissive access level.
B. private - access is limited to the containing type. The least permissive level.
C. protected - access is limited to the containing class, or types derived from the containing class.
D. internal - access is limited to the current assembly.
E. protected internal - access is limited to the current assembly or types derived from the containing class.

Back


12. Answer is:
protected and protected internal access modifiers are not allowed for nested struct because the struct type is sealed (does not support inheritance).

Back


13. Answers are:

A. class (nested) = private
B. class (not nested) = internal
C. struct (nested)= private
D. struct (not nested)= internal
E. enum = public
F. interface = public


Back


14. Answer is:
C and D. enum and interface do not allow you to declare accessibility levels. They are always public.

Back


15. Answers are:
Besides the access modifiers, list and explain 5 other modifiers for the class type:

A. abstract - Indicates a missing or incomplete implementation. An abstract class is intended only to be a base class. An abstract class can not be instantiated or modified as sealed. Any non-abstract class derived from an abstract class must include the implementation of all the abstract members.

B. partial - A partial class can be split into multiple pieces, and stored in two or more source files.

C. sealed - Specifies that a class cannot be inherited.

D. static - A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. Because there is no instance of the class, you access the members of a static class by using the class name itself. A static class is sealed (can not be inherited), so it limits future enhancements ... so use them wisely. A static class can only have static members; can not be instantiated; is sealed; and cannot contain instance constructors.

E. unsafe - The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. C# does not support pointer arithmetic, by default. Using unsafe code introduces security and stability risks. Unsafe code is required when you call native functions that require pointers. In order for C# to compile unsafe code, the application must be compiled with /unsafe.

Back


16. Answers are:
Besides the access modifiers, list and explain 8 other modifiers for methods:

A. abstract - an abstract method is an incomplete implementation containing only the method signature and not the method body. The method body must be specified in the derived class. Abstract methods are only allowed in abstract classes. An abstract method is implicitly also a virtual method. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

B. async - An async method provides a convenient way to do potentially long-running work without blocking the caller's thread. The async and await keywords in C# are the heart of asynchronous programming.The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. An async method can't declare any ref or out parameters, but it can call methods that have such parameters. The name of an async method, by convention, ends with an "Async" suffix.

Eric Lippert's explanation from MSDN Magazine article Easier Asynchronous Programming with the New Visual Studio Async CTP:

The CLR 4 release defined the type Task—the workhorse type of the Task Parallel Library (TPL)—to represent the concept of “some work that’s going to produce a result of type T in the future.” The concept of “work that will complete in the future but returns no result” is represented by the non-generic Task type.

Precisely how the result of type T is going to be produced in the future is an implementation detail of a particular task; the work might be farmed out to another machine entirely, to another process on this machine, to another thread, or perhaps the work is simply to read a previously cached result that can be accessed cheaply from the current thread. TPL tasks are typically farmed out to worker threads from a thread pool in the current process, but that implementation detail is not fundamental to the Task type; rather, a Task can represent any high-latency operation that produces a T.

Stephen Cleary's advice from MSDN Magazine article Best Practices in Asynchronous Programming:

There are three possible return types for async methods: Task, Task<T> and void, but the natural return types for async methods are just Task and Task<T>. ... “Async all the way” means that you shouldn’t mix synchronous and asynchronous code without carefully considering the consequences. In particular, it’s usually a bad idea to block on async code by calling Task.Wait or Task.Result. ... Finally, some async-ready data structures are sometimes needed. TPL Dataflow provides a BufferBlock<T> that acts like an async-ready producer/consumer queue. Alternatively, AsyncEx provides AsyncCollection<T>, which is an async version of BlockingCollection<T>.

Visual Studio article Asynchronous Programming with Async and Await (C# and Visual Basic) explains:

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

Article on how the Futures and promises constructs used for synchronizing in some concurrent programming languages:

In computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete. ... In other cases a future and a promise are created together and associated with each other: the future is the value, the promise is the function that sets the value – essentially the return value (future) of an asynchronous function (promise).

C. extern - Indicates the method is implemented externally, typically using a language other than C#. Because an external method declaration provides no actual implementation, the method-body of an external method simply consists of a semicolon. A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code.

[DllImport("avifil32.dll")]
private static extern void AVIFileInit();

D. new - Explicitly hides a member that is inherited from a base class. Not to be confused with the "new" operator or the "new" constraint..

E. override - Extends the base class method. Can be use on virtual methods and must be used on abstract methods.

F. partial - Allows the method signature and method body to be split into different pieces of code. Partial methods act as hooks for plugging in code, usually for generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. If the partial method has no implementation, then the compiler removes the partial method and any calls to the partial method.

G. unsafe - The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. C# does not support pointer arithmetic, by default. Using unsafe code introduces security and stability risks. Unsafe code is required when you call native functions that require pointers. In order for C# to compile unsafe code, the application must be compiled with /unsafe.

H. virtual - Allows the method to be changed in derived classes (i.e. use "override" in derived class). By default, methods are non-virtual and you can not override a non-virtual method. The virtual modifier can not be used with the static, abstract, private, or override modifiers. When you define new methods or properties in a class, you can prevent deriving classes from overriding them by not declaring them as virtual.

Back


17. Answers are:
Besides the access modifiers, list and explain 4 other modifiers for fields:

A. const - Specifies that the value of the field or the local variable cannot be modified.

B. static - Indicates the variable belongs to a type, and not an instance of the type. Static variables are globally visible across the application domain and will persist for the duration of the application domain.

C. readonly - Declares a field that can only be assigned values as part of the declaration or in a constructor in the same class.

D. volatile - Is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declared volatile. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

Back


18. Answer is:

namespace abstractClass
{
    abstract class CalcClass // Abstract Class (for Base Class)
    {
        protected int x = 13;
        protected int y = 6;
        public abstract int DoOperation(); // Abstract Method
        public abstract int X { get; }
        public abstract int Y { get; }
    }

    class Adder : CalcClass // Derived Addition Class
    {
        public override int X { get { return x; } }
        public override int Y { get { return y; } }

        public override int DoOperation()
        {
            return x + y;
        }
    }

    class Subtractor : CalcClass // Derived Subtraction Class
    {
        public override int X { get { return x; } }
        public override int Y { get { return y; } }

        public override int DoOperation()
        {
            return x - y;
        }
    }

    class Program
    {
        static void Main()
        {
            System.Console.WriteLine("Abstract Class with Abstract Method.");
            System.Console.WriteLine("Classes derived from an abstract class with different method implementations.");
            System.Console.WriteLine("Operands: (13,6).\n");
            // Prints: Adder result is: 19
            System.Console.WriteLine("\n------- DoOperation Method from Adder Derived Class -------");
            Adder myAdder = new Adder();
            System.Console.WriteLine("Adder.DoOperation() result is: {0}", myAdder.DoOperation());

            // Prints: Subtractor result is: 7
            System.Console.WriteLine("\n------- DoOperation Method from Subtractor Derived Class -------");
            Subtractor mySubtractor = new Subtractor();
            System.Console.WriteLine("Subtractor.DoOperation() result is: {0}", mySubtractor.DoOperation());

            System.Console.WriteLine();
        }
    }
}

Back


19. Answers are:

A. A namespace can directly contain fields and methods.
(Answer = False - A namespace can not directly contain fields and methods.)

B. Abstract methods are only permitted inside abstract types.
(Answer = True - e.g. abstract methods are only permitted inside abstract classes.)

C. An abstract method is implicitly also a virtual method.
(Answer = True - however the abstract method can not have a virtual modifier.)

D. It is possible to split the definition of a class or a struct, an interface or a method over two or more source files.
(Answer = True - It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

Back


20. Answer is:
Answer true or false to the following statements about partial methods

A. A partial method can only be declared within a partial class or partial struct.
(Answer = True - A partial method must be declared within a partial call or a partial struct).

B. A partial method can split the implementation of a method.
(Answer = False - A partial can only define the implementation (method body) in either zero or one of the partial methods. i.e. "a partial method may not have multiple implementing declarations". A partial method consists of two parts: the definition (method signature) and the implementation. The implementation is optional).

C. A partial method can return a value.
(Answer = False - "Partial methods must have a void return type".)

D. A partial method can have an access modifier of "public".
(Answer = False - Partial methods can not have any access modifiers; their access level must be allowed to default to "private". "A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers".)

E. A partial method must always have an implementation.
(Answer = False - A partial method does not require an implementation. If the partial method has no implementation, then the compiler removes the partial method and any calls to the partial method. Partial methods act as hooks for plugging in code, usually for generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.

F. A partial method can have "ref" and "out" parameters.
(Answer = False - A partial method can have "ref" parameters, but not "out" parameters. i.e. "A partial method cannot have out parameters".

G. A partial method can be static or generic.
(Answer = True - A partial method can be static or generic.)

H. You can make a delegate to a partial method that has been defined and implemented.
(Answer = True - You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.)

Back


21. Answer is:
If a member is nested within another type, its accessibility is determined by:

A. The accessibility level of the member, and
B. The accessibility domain of the immediately containing type. (i.e. The accessibility domain of a nested type never exceeds that of the containing type).

Back


22. Answer is:
C, F, G, H, and I are not accessible due to their protection level.

namespace accessdomain
{   
    public class Outer
    {
        public static int publicInt;
        internal static int internalInt;
        private static int privateInt = 0;

        static Outer()
        {
            // Outer class can access public or internal members
            // in a public, private, or internal nested class
            Inner1.publicInt = 1;
            Inner1.internalInt = 2;
            Inner2.publicInt = 3;
            Inner2.internalInt = 4;
        }

        public class Inner1
        {
            public static int publicInt;
            internal static int internalInt;
            private static int privateInt = 0;
        }

        private class Inner2
        {
            public static int publicInt = 0;
            internal static int internalInt = 0;
            private static int privateInt = 0;
        }
    }

    class MainClass
    {
        static void Main()
        {
            Outer.publicInt = 1; // A. Access is unlimited
            Outer.internalInt = 2; // B. Accessible only in current assembly
            //Outer.privateInt = 3;   // C. Compiler Error: inaccessible outside of class Outer

            Outer.Inner1.publicInt = 1; // D. Access is unlimited           
            Outer.Inner1.internalInt = 2; // E. Accessible only in current assembly
            //Outer.Inner1.privateInt = 3;  // F. Compiler Error: inaccessible outside of class Inner1
           
            //Outer.Inner2.publicInt = 1;  // G. Compiler Error: inaccessible outside of class Outer            
            //Outer.Inner2.internalInt = 2; //H.  Compiler Error: inaccessible outside of class Outer
            //Outer.Inner2.privateInt = 3; // I. Compiler Error: inaccessible outside of class Inner2
        }
    }
}

Back


23. Answer is:
Name the only two places where a "readyonly" field can be assigned a value.
A. In the field declaration.
B. In a constructor.

Back


24. Answer is:
Explain the difference between a "readonly" field and a "const" field.
A readonly field is a runtime constant while a const field is a compile-time constant. That is, a const field can only be initialized at the declaration of the field while a readonly field can be initialized at either the declaration or in a constructor. So a const field will always have the same value each time the program is run, but the readonly field may contain different values depending upon which constructor was run.

Back


25. Answer is:
Explain why the keyword "this" is not valid in a property, method, or field which has the "static" modifier?
The keyword "this" refers to the current instance of an object. The "static" modifier prevents the member from every being instantiated. With the static modifier the member belongs to the type itself, rather than a specific object. This requires static members to be prefixed with the type name, as opposed to the object name.

Back


26. Answer is:
global:: refers to the global namespace. The global namespace is the "root" namespace for any C# program and is not named. For example the namespaceglobal::System will always refer to the .NET Framework namespace System.

Back


27. Answer is:
In C#, what is the recommended way to create fields that have global scope (if you really must)?
A. Put all the variables (that are to have global scope) inside a single static class. Use a meaningful class name that will indicate these are globals (e.g. "Globals").
B. Use Properties, as opposed to fields. This will provide a way to address any issues with concurrent access that might arise.


public static class MyGlobals
{
public static int myGlobalInt1 {get; set;}
}

Back


28. Answer is:

A. If you declare a constructor for a class that has no parameters, it may be referred to as the "default constructor". Additionally the constructor automatically created by the compiler when no constructor is defined is also referred to as the "default constructor".
(Answer = True)

B. structs cannot contain an explicit default constructor (i.e. constructor with no parameters) because one is provided automatically by the compiler.
(Answer = True)
structs can not explicitly define parameter-less constructors. Constructors for structs must have one or more parameters.

C. You can chain constructors together by having one constructor call another.
(Answer = True)

D. An instance constructor is the same as a static constructor.
(Answer = False)
On instance constructor executes once per instance while a static constructor executes once per type.
Instance constructors create and initialize instance member variables when the "new" expression is used to create an object.
A static constructor initialized the class only once; before the first instance is created or any static members are referenced.

E. You will not be able to create an object if the corresponding class constructor has an access modifier of "private".
(Answer = True)

F. The compiler will attempt to create a constructor for a class if no constructor is declared.
(Answer = True)

G. You can access static members from a non-static (normal) constructor.
(Answer = True)

H. You can access non-static (normal) members from a static constructor.
(Answer = False)

I. Constructors can not have a return type.
(Answer = True)

J. Constructors can be overloaded. i.e. A class or struct may have multiple constructors that take different number and kinds of arguments.
(Answer = True)


Back


29. Answer is:

A. An enum can be directly define within a namespace (i.e. outside of a class or struct).
(Answer = True - In fact they are usually declared directly in a namespace so they are available to all classes. This is not true of fields or methods however, they must be defined with a class or struct.)

B. By default the first enumerator corresponds to value 1, and each successive enumerator is increased by 1.
(Answer = False - By default the first enumerator corresponds to value 0, and each successive enumerator is increased by 1.)

C. Enumerators can use initializers to override the default values.
(Answer = True)

D. Every enumeration must have an underlying integral type, with the default underlying type being an int.
(Answer = True)

E. Which of the following are valid underlying integral types for enumerations (byte, sbyte, short, long, char).
char is not a valid underlying type for enumerators.

F. You can explicitly assign some of the enum members without assigning values to others.
(Answer = True - The unassigned enum members keep incrementing from the last explicit value.)

G. An enumerator can have white space in its name.
(Answer = False - An enumerator can not have white space in its name.)

H. An explicit cast is required to convert the enum type to its underlying integral type.
(Answer = True - e.g. int x = (int) Days.Sunday;)

I. The Enum methods GetName and GetValue return the constant name and underlying value.
(Answer = True)L

J. It is recommended that all Enum declarations should start with a zero value.
(Answer = True - use None=0 if you are going to start the enums at a non-zero value.)

K. You can add a member to an enumeration at run-time.
(Answer = False - You cannot add an enumeration member at run-time.)

L. Enum extension methods must be defined in a top level static class. They can not be in a nested or in non-static classes.
(Answer = True)

M. An extension method will never be called if it has the same signature as a method defined in a type.
(Answer = True Instance methods have priority.)

N. The attributes [Flags] and [FlagsAttribute] have the same meaning.
(Answer = True- Flags is shorthand for FlagsAttributes. Flags enumerations are used for masking bit fields and doing bitwise comparisons (Must use powers of two for the bitwise comparisons to work)).

O. The [FlagsAttribute] should only be used on an enumeration if a bitwise operation is to be performed on the enumeration value.
(Answer = True)


Back


30. Answer is:


Back

1. Ad-hoc
A. Overloading (C# - Method and Operator Overloading)
B. Coercion (C# - Implicit Casting)
2. Universal
A. Parametric (C# - Generics)
B. Inclusion a.k.a. subtyping (C# Inheritance and Interfaces)


31. Answer is:
upcasting - converting an instance of a derived class to its base class, (i.e. going up the inheritance hierarchy tree).
downcasting - converting an instance of a base class to one of its derived classes, (i.e. going down the inheritance hierarchy tree).

/**************************************************************************************
* Upcasting and Downcasting an object does NOT change the object's type              *
* (like casting does with primitives). Instead object casting creates                *
* reference variables which control the types of behaviors which can be performed    *
* against the object. In the example below a Toaster is created, but then it is      *
* upcast to an Appliance. The Toaster reference can make toast, while the Appliance  *
* reference can not ... even though both references are pointing to the same Toaster *
* object.  Downcasting the Appliance back to a Toaster provides another reference    *
* that can be used to call the object's MakeToast() method once again                *
**************************************************************************************/
namespace UpCastingAndDownCasting
{
    class Appliance {}
    class Toaster : Appliance
    {
        protected int toasterNumber = 0;
        public Toaster(int toasterNumber=0) { this.toasterNumber = toasterNumber; }
        public void MakeToast(string referenceName, string toastType="Nothing" )
        {       
            System.Console.WriteLine("MakeToast: {0} is toasting {1} in toaster number {2}", referenceName, toastType, toasterNumber);
        }
    }
   
    class Program
    {
        static void Main()
        {
            System.Console.WriteLine("Upcasting/Downcast of Objects:");
            System.Console.WriteLine(" Same object, but permitted behaviors depend upon the behaviors");
            System.Console.WriteLine("assocated with the type of the reference variable.\n");
            // Create a Toaster and make toast.
            Toaster myToaster = new Toaster(1);
            System.Console.WriteLine("\n1. myToster is born a Toaster.");
            System.Console.WriteLine("Born: Toaster myToaster = new Toaster(1);");
            myToaster.MakeToast("myToaster", "Waffle");     // Valid - Toaster object can make toast

            /**********************************************************
             * Upcast reference myToaster to an Applicance.           *
             * Object is still a Toaster, but new reference to        *
             * it (myAppliance) will only perform Applicance methods. *
             **********************************************************/
            Appliance myAppliance = myToaster; // Upcast            
            // Using myApplicance Reference, Toaster can no longer make toast
            //myAppliance.MakeToast("myApplicane","Pop Tart"); - Not a valid method call
            System.Console.WriteLine("\n2. Upcast Toaster to Appliance, can no longer make toast.");
            System.Console.WriteLine("Upcast: Appliance myAppliance = myToaster;");
            System.Console.WriteLine("Why can't I toast? I am the same Toast object.\n");

            /***************************************************************
             * Downcast reference myAppliance back to a Toaster.           *
             * myAppliance and myToaster are the same Object, but new      *
             * Toast type reference (cathyToaster) allows it to make toast.*
             ***************************************************************/           
            Toaster cathyToaster = (Toaster)myAppliance; // Downcast
            System.Console.WriteLine("3. Downcast Appliance back to a Toaster, can once again make toast.");
            // Using new cathyToaster Reference, Toast can make toast again
            System.Console.WriteLine("Downcast: Toaster cathyToaster = (Toaster)myAppliance;");
            cathyToaster.MakeToast("cathyToaster","Bagel");
          
            // myToaster, myAppliance, and cathyToaster reference the same object,
            // they just permit different behaviors depending on which reference used.
            System.Console.WriteLine("\n--- Equality Tests ---");
            System.Console.WriteLine("Is myToaster the same object as myAppliance: {0}",
                                      myToaster.Equals(myAppliance)); // Prints true
            System.Console.WriteLine("Is cathyToaster the same object as myToaster: {0}",
                                      cathyToaster.Equals(myToaster)); // Prints true

            System.Console.WriteLine("\n--- Type Tests ---");
            System.Console.WriteLine("myToaster    is an {0}", myToaster.GetType()); // Prints: Toaster
            System.Console.WriteLine("myApplicance is an {0}", myAppliance.GetType());// Prints: Toaster
            System.Console.WriteLine("cathyToaster is an {0}\n", myAppliance.GetType());// Prints: Toaster
        }
    }
}

Back


32. Answer is:
What happens when a cast fails when using the "as" operator?
When upcast fails using the "as" operator, the reference variable is set to null and an exception is NOT thrown.

Back


33. Answer is:
Explain the special needs object-oriented languages have for polymorphism and give the definition of polymorphism usually associated with object-oriented languages.
In object-oriented languages, polymorphism is used to allow a runtime determination of which method to invoke based upon an object's type.

Back


34. Answer is:
C# calls it a base class, but what is it called in Java?
Parent Class = base class (C#) = superclass (Java)

Back


35. Answer is:
C# calls it a derived class, but what is it called in Java?
Child Class = derived class (C#) = subclass (Java)

Back


36. Answer is:
What feature is required in order for a programming to support polymorphism?
Dynamic Binding is required to support polymorphism.

Back


37. Answer is:
Choose which one of these methods is the most efficient method at casting reference types and explain why:
Use the "as" operator and check the reference variable for null to see if the cast succeeded, because
the "is" operator method requires testing the cast twice, once for the "is" and again during the cast, and
testing for null is more efficient than handling an exception.

Back


38. Answer is:
When polymorphism and inheritance are tightly linked because of static type checking, what component can be used to weaken the link and provide the class with more flexibility?
The concept of interface to weaken the link between inheritance and polymorphism.

Back


39. Answer is:
. In NET 4.0 extension methods were introduced. What is the purpose of extension methods and how should they be declared?
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are declared as a special kind of static method, but they are called as if they were instance methods on the extended type.

Back


40. Answer is:
How are indexers used? Write code to show how they are used.
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

namespace IndexerExample
{
    class PeopleList
    {
        public const int size = 4;
        private string[] theList = new string[size] {"John", "Nick", "Nancy", ""};
        public string this[int index]
        {
            get { return theList[index]; }
            set { theList[index] = value; }
        }
    }

    class Program
    {
        static void Main()
        {
            PeopleList myList = new PeopleList();
            myList[3] = "Sue";
            for (int i = 0; i < PeopleList.size; i++ )
                System.Console.Write("{0} ", myList[i]); // Prints: John Nick Nancy Sue
            System.Console.WriteLine();
        }
    }
}

Back


41. Answer is:
What is the Law of Demeter (LoD)?
LoD is a set of design guidelines developed by Ian Holland at Northeastern University (Boston) in 1987. LoD seeks to reduce unnecessary coupling in object-oriented programs by establishing a set of limiting guidelines governing how one object may access another. The LoD guidelines create a shallow relationship between objects which reduces the number of classes which may be affected by changes within the system. A less presumptuous name for LoD has been proposed as "The Principle of Least Knowledge" which is defined as:

A component should take on no more knowledge about another than is absolutely necessary to perform an inherent concern.

Whereas the LoD is commonly defined as:

For any class C, a method M belonging to C may only invoke other methods belonging to the following:

  • Class C
  • Members of C
  • Parameters of M
  • Objects created by M
  • Objects created by other methods of class C called by M
  • Globally accessible objects


    Back


    42. Answer is:
    Write a method and a method call that uses both named and optional parameters.

    /* Example of Named and Optional Parameters */
    namespace Parameters
    {

        class Program
        {
            static void theMethod(int nParm1, int nParm2, int oParm3=3)
            {
                System.Console.WriteLine("{0},{1},{2}",nParm1, nParm2, oParm3);
            }

            static void Main()
            {
                theMethod(nParm2:2, nParm1:1); // Prints: 1,2,3
            }
        }
    }

    Back


    43. Answer is:
    What does the compiler do behind the scenes when a value type is declared as a nullable type?
    Nullable types are instances of the System.Nullable struct. For example adding a question mark to any value type (e.g. int?) causes the compiler to translate the type into a Nullable struct that includes a field to store the original value plus a Boolean field (HasValue) to indicate if the value is set to null. C# nullable type also supports a Coalescing operator (??) for assigning another value in the case where the variable is null.

    int? x = null;
    int j;

    // Coalescing Operator
    j = x ?? 0;

    // Equivalent code to Coalescing Operator

    if (x.HasValue)
        j = x.Value;
    else
        j = 0;

    Back


    44. Answer is:
    Code an example of constructor chaining.

    /* Example of Constructor Chaining */
    using System;
    namespace Cchaining
    {
        public class theClass
        {
            public int _x;
            public int _y;
            public int _z;

            public theClass() : this(0) { Console.WriteLine("No Parm Constructor, (_x = {0})", _x); }

            public theClass(int a) : this(a, 0) {Console.WriteLine("One Parm Constructor (_x = {0})", _x); }

            public theClass(int a, int b) : this(a, b, 0) { _x = a; _y = b; Console.WriteLine("Two Parm Constructor (_x = {0}, _y = {1})", _x, _y); }

            public theClass(int a, int b, int c) { _x = a; _y = b; _z = c; Console.WriteLine("Three Parm Constructor (_x = {0}, _y = {1}, _z = {2})", _x, _y, _z); }
        }

        class Program
        {

            static void Main()
            {
                Console.WriteLine("--- No Parameter Constructor: theClass() ---");
                theClass myClass = new theClass();
                Console.WriteLine("-- From Main: myClass._x = {0}", myClass._x); // Prints: _x = 10
                Console.WriteLine("-- From Main: myClass._y = {0}", myClass._y); // Prints: _y = 20
                Console.WriteLine("-- From Main: myClass._z = {0}", myClass._z); // Prints: _z = 30

                Console.WriteLine("\n--- One Parameter Constructor: theClass(100) ---");
                theClass myClass1 = new theClass(100);
                Console.WriteLine("-- From Main: myClass1._x = {0}", myClass1._x); // Prints: _x = 100
                Console.WriteLine("-- From Main: myClass1._y = {0}", myClass1._y); // Prints: _y = 20
                Console.WriteLine("-- From Main: myClass1._z = {0}", myClass1._z); // Prints: _z = 30

                Console.WriteLine("\n--- Two Parameter Constructor: theClass(1000, 2000) ---");
                theClass myClass2 = new theClass(1000, 2000);
                Console.WriteLine("From Main: myClass2._x = {0}", myClass2._x); // Prints: _x = 1000
                Console.WriteLine("From Main: myClass2._y = {0}", myClass2._y); // Prints: _y = 2000
                Console.WriteLine("From Main: myClass2._z = {0}", myClass2._z); // Prints: _z = 30


                Console.WriteLine("\n--- Three Parameter Constructor: theClass(10000, 20000, 30000) ---");
                theClass myClass3 = new theClass(10000, 20000, 30000);
                Console.WriteLine("From Main: myClass3._x = {0}", myClass3._x); // Prints: _x = 10000
                Console.WriteLine("From Main: myClass3._y = {0}", myClass3._y); // Prints: _y = 20000
                Console.WriteLine("From Main: myClass3._z = {0}", myClass3._z); // Prints: _z = 30000

                Console.WriteLine();
            }
        }
    }

    .Constructor Chaining

    Back


    45. Answer is:
    Define the Big Ball of Mud principle.
    A big ball of mud is a software system that lacks a perceivable architecture. Although undesirable from an engineering point of view, such systems are common in practice due to business pressures and developer turnover. They considered to be a design anti-pattern.

    Back


    46. Answer is:
    What are the principles of SOLID in object-oriented design?
    S - Single Responsibility: a class should have only a single responsibility.
    O - Open-closed: “software entities … should be open for extension, but closed for modification”.
    L - Liskov Substitution: “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”.
    I - Interface Segregation: “many client-specific interfaces are better than one general-purpose interface.”
    D - Dependency Inversion: one should “Depend upon Abstractions. Do not depend upon concretions.”

    Back


    47. Answer is:
    What must you do prior to a downcast in order for the downcast to be successful?
    You must upcast prior to downcasting in order for the downcast to be successful. Downcasting is how you take a previously upcast reference and change it back. Upcast is checked at compile time so they are always successful. Downcast is checked at runtime and can result in an InvalidCastException if the types are not compatible. Use the "is" and "as" operators to avoid an InvalidCastException when downcasting.
    Back


    48. Answer is:
    What is the purpose of an Interface?
    An interface loosens the coupling between polymorphism and inheritance that arises because the language is statically typed. In C# and Java a class can only inherit from a single class, however they can implement multiple interfaces. The interfaces form contractual obligation to implement certain methods, properties and events ... which can come from multiple sources.

    Back


    49. Answer is:
    How does an interface differ from a class?
    An interface is a pattern that describes the behavior while a class performs the behavior.
    An interface contains only the signatures for a set of members. The implementation of the members are performed in the class or struct that implements the interface. Interfaces are used to achieve an effect similar to multiple inheritance, while classes only support single inheritance. Interfaces allow the inclusion of behavior from multiple sources in a class.

    A class both defines and implements each member. A class can only inherit from one class, but it can implement multiple interfaces. A class can have access modifiers while an interface can not. By default everything in an interface has public access. Class members can be made static, while interface members can not be made static. Classes contain data members and constructors, while interfaces do not. Also a struct can not inherit from a class, but a struct can implement an interface. That is, you must use an interface if want to simulate inheritance for a struct.

    Back


    50. Answer is:
    Respond true or false to the following statements about interfaces

    A. An interfaces can extend another interface.
    (Answer = True - Some will say an interface can inherit from another interface, but many prefer the term "extends" as being more correctly)
    B. The "is" operator can be used to determine if a class implements an interface. (true)
    (Answer = True - Example below.)
    if (theObject is ICloneable)
    {
      ICloneable iCloneable = (ICloneable) theObject;
    }
    else
    {
      console.WriteLine (" ICloneable interface is not supported");
    }
    C. An interface can be instantiated.
    (Answer = False)
    D. You can upcast and downcast with interfaces.
    (Answer = True)
    E. A class can implement only one interface.
    (Answer = False)
    F. A struct can implement an interface, but a struct can not inherit from a class.
    (Answer = True)

    Back


    51. Answer is:
    Why is an abstract class like a cross between a class and an interface?
    Interfaces are similar to abstract classes in that neither one can be instantiated. The abstract class can only be used for a base class and the derived class must complete all implementations from the base class. Likewise, all the contractual details in interfaces must be implemented in the classes that implement the interfaces. An abstract class can implement some of the behaviors and leave other behaviors to be implemented by the derived class. However, an interface can not implement any of the behaviors and all the behaviors must be implemented by the class which implements the interface.

    Back


    52. Answer is:
    How are the following interfaces used:

    A. IEnumerable and IEnumerator: for use with foreach and LINQ - Exposes an enumerator, which supports a simple iteration over a non-generic collection.

    B. IDisposable: for resources requiring cleanup, used with "using" - Defines a method to release allocated resources. Use the "Dispose" method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

    C. IQueryable: lets you execute requests against queriable data sources - Provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified.

    D. INotifyPropertyChange: for data binding to UI classes in WPF, winforms and Silverlight - The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

    E. IComparable and IComparer: for generalized sorting - Is implemented by types whose values can be ordered or sorted. It requires that implementing types define a single method, CompareTo(Object), that indicates whether the position of the current instance in the sort order is before, after, or the same as a second object of the same type.

    F. IEquatable and IEqualityComparer: for generalized equality - Is implemented by types whose values can be equated (for example, the numeric and string classes). A value type or class implements the Equals method to create a type-specific method suitable for determining equality of instances.

    G. IList: represents a non-generic collection of objects that can be individually accessed by index - IList is a descendant of the ICollection interface and is the base interface of all non-generic lists.

    H. IDictionary: represents a generic collection of key/value pairs - Each pair must have a unique key. Implementations can vary in whether they allow key to be null. The value can be null and does not have to be unique. The IDictionary<TKey, TValue> interface allows the contained keys and values to be enumerated, but it does not imply any particular sort order.

    I. ICollection: defines methods to manipulate generic collections. - The ICollection interface is the base interface for classes in the System.Collections.Generic namespace. If neither the IDictionary<TKey, TValue> interface nor the IList<T> interface meet the requirements of the required collection, derive the new collection class from the ICollection<T> interface instead for more flexibility.

    Back


    53. Answer is:
    Write code that illustrates the difference between an instance constructor and a static constructor.
    namespace constructors
    {
        class TheClass
        {
            // Instance Constructor
            public TheClass()
            {
                System.Console.WriteLine("Instance Constructor");
            }
            // Static Constructor
            static TheClass()
            {
                System.Console.WriteLine("Static Constructor");
            }
        }

        class Program
        {
            static void Main()
            {
                /*Prints:
                 * Static Constructor
                 * Instance Constructor
                 * ----------------------
                 * Instance Constructor
                 */
                TheClass myClass = new TheClass(); // Prints both constructors
                System.Console.WriteLine("-----------------------");
                TheClass myClass2 = new TheClass(); // Prints only instance constructor
                System.Console.WriteLine();
            }
        }
    }
    Back


    54. Answer is:
    What is the difference between the GetType() method and the typeof operator?

    Back


    55. Answer is:
    Why are friend assemblies used?

    Back


    56. Answer is:
    Why are friend assemblies used?

    Back


    57. Answer is:
    What is "reimplementing an interface" and what problems can it cause?

    Back


    58. Answer is:
    What is the difference between generics and inheritance?

    Back


    59. Answer is:
    Compare and contrast Covariance and Contravariance as they apply to generics.

    Back


    60. Answer is:
    Explain generic constraints and provide a coding example.

    Back


    61. Answer is:
    What is the purpose of generics?

    Back


    62. Answer is:
    What are two purposes of the base keyword?

    Back


    63. Answer is:
    Explain boxing and unboxing.

    Back


    64. Answer is:
    Code an example of a class that implements more than one interface.

    Back


    Explain what it means when they say: "inheritance is transitive".
    65. Answer is:

    Back


    66. Answer is:
    Define encapsulation and explain how it is supported in C#.

    Back


    67. Answer is:
    Name the only two modifiers allowed for static constructors.
    extern and safe

    Back


    68. Answer is:
    Define a delegate and list its uses.
    A delegate is a class that defines a type that encapsulates a method with a particular set of arguments and return type. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

    • Delegates allow methods to be passed as parameters.
    • Delegates can be used to define callback methods.
    • Delegates can be chained together; for example, multiple methods can be called on a single event.

    In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 lambda expressions supersede anonymous methods as the preferred way to write inline code.


    Back


    69. Answer is:
    Static Polymorphism is sometimes called Method Overloading while Dynamic Polymorphism is called Method Overriding.

    Back


    70. Answer is:

    Back


    71. Answer is:

    Back


    72. Answer is:

    Back


    73. Answer is:

    Back


    74. Answer is:

    Back


    75. Answer is:
    Anonymous Methods (C# Programming Guide)

    Back


    76. Answer is:

    Back


    77. Answer is:

    Back


    78. Answer is:

    Back


    79. Answer is:

    Back


    80. Answer is:

    Back


    81. Answer is:

    Back


    82. Answer is:

    Back


    83. Answer is:

    Back


    84. Answer is:

    Back


    85. Answer is:

    Back


    86. Answer is:

    Back


    87. Answer is:

    Back


    88. Answer is:

    Back


    89. Answer is:

    Back


    90. Answer is:

    Back


    91. Answer is:

    Back


    92. Answer is:

    Back


    93. Answer is:

    Back


    94. Answer is:

    Back


    95. Answer is:

    Back


    96. Answer is:

    Back


    97. Answer is:

    Back


    98. Answer is:

    Back


    99. Answer is:

    Back


    100. Answer is:

    Back

    C# Type CrossWord Puzzle

    .C# Types


    Across
    1. Operator used to check type compatibility.
    2. Modifier indicating a class will not be instantiated. 
    5. Keyword used to refer to the current instance of an object. 
    7. Type of a class. 
    10. Access modifier restricting to current assembly.
    14. Keyword to indicate the parameter is an input/output parameter.
    15. Keyword used to refer to the base class of an object.
    18. Casts a base class back to its derived class.
    20. Modifier which prevents the class from being inherited.
    23. Explicitly converting a value type to a reference type. 
    24. Methods which control how class fields are set. 
    26. Operator which performs a cast. 
    
    Down
    1. Specified the members that will be implemented by the class or structure. 
    3. Name of method used to obtain the dynamic (runtime) type of an instance.
    4. The ultimate base class for all types.
    6. Access modifier restricting to containing class or derived classes.
    8. The name for a method which allows for adding new capabilities to a type without modifying the type.
    9. Modifier that allows a method to be overridden in derived classes. 
    11. Type of a struct. 
    12. Provides a way to access elements in a class or a struct that encapsulates a list of values. 
    13. Modifier that hides a member that is inherited from a base class. 
    16. Context required for using pointers in C#. 
    17. Allows reusability by providing a parameter for specifying the type.
    19. A term used to indicate a sequence of constructors calling other constructors.
    21. Modifier indicating a missing or incomplete implementation. 
    22. One of the two places where a read-only field can be assigned a value. 
    25. A value type that lets you specify a set of named numeric constants. 
    




    Answers


    Across
    1. Operator used to check type compatibility. (is)
    2. Modifier indicating a class will not be instantiated. (static)
    5. Keyword used to refer to the current instance of an object. (this)
    7. Type of a class. (reference)
    10. Access modifier restricting to current assembly. (internal)
    14. Keyword to indicate the parameter is an input/output parameter. (ref)
    15. Keyword used to refer to the base class of an object. (base)
    18. Casts a base class back to its derived class. (downcast)
    20. Modifier which prevents the class from being inherited. (sealed)
    23. Explicitly converting a value type to a reference type. (boxing)
    24. Methods which control how class fields are set. (properties)
    26. Operator which performs a cast. (as)
    
    Down
    1. Specified the members that will be implemented by the class or structure. (interface)
    3. Name of method used to obtain the dynamic (runtime) type of an instance. (GetType)
    4. The ultimate base class for all types. (object)
    6. Access modifier restricting to containing class or derived classes. (protected)
    8. The name for a method which allows for adding new capabilities to a type without modifying the type. (extension)
    9. Modifier that allows a method to be overridden in derived classes. (virtual)
    11. Type of a struct. (value)
    12. Provides a way to access elements in a class or a struct that encapsulates a list of values. (indexer)
    13. Modifier that hides a member that is inherited from a base class. (new)
    16. Context required for using pointers in C#. (unsafe)
    17. Allows reusability by providing a parameter for specifying the type. (generics)
    19. A term used to indicate a sequence of constructors calling other constructors. (chaining)
    21. Modifier indicating a missing or incomplete implementation. (abstract)
    22. One of the two places where a read-only field can be assigned a value. (constructor)
    25. A value type that lets you specify a set of named numeric constants. (enum)