Showing posts with label c# faqs. Show all posts
Showing posts with label c# faqs. Show all posts

C# interview faqs mostly asked questions in interview

C# interview questions
1 Describe the difference between a Thread and a Process?

2 What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

3 What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory
for the system? How would this affect a system design?

4 What is the difference between an EXE and a DLL?

5 What is strong-typing versus weak-typing? Which is preferred? Why?

6 Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.

7 What is a PID? How is it useful when troubleshooting a system?

8 How many processes can listen on a single TCP/IP port?

9 What is the GAC? What problem does it solve?

10 What is serialization in .NET? What are the ways to control serialization?

11 Does C# support multiple inheritance?

12 What’s the implicit name of the parameter that gets passed into the class’ set method?

13 What’s the top .NET class that everything is derived from?

14 How’s method overriding different from overloading?

15 What is CLR?

16 What is CTS?

17 What is CLS?

18 What is strong name?

19 What is Application Domain?

20 Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

21 Describe what an Interface is and how it’s different from a Class.

22 What is Reflection?

23 What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

24 Are the type system represented by XmlSchema and the CLS isomorphic?

25 Conceptually, what is the difference between early-binding and late-binding?

26 Is using Assembly.Load a static reference or dynamic reference?

27 When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?

28 What is an Asssembly Qualified Name? Is it a filename? How is it different?

29 Is this valid? Assembly.Load("foo.dll");

30 How is a strongly-named assembly different from one that isn’t strongly-named?

31 Can DateTimes be null?

32 What is the JIT? What is NGEN? What are limitations and benefits of each?

33 How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?

34 What is the difference between Finalize() and Dispose()?

35 How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?

36 What does this useful command line do? tasklist /m "mscor*"

37 What is the difference between in-proc and out-of-proc?

38 What technology enables out-of-proc communication in .NET?

39 When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

40 What is FullTrust? Do GAC’ed assemblies have FullTrust?

41 What are Satellite Assemblies?

42 What is Global Assembly Cache (GAC) and what is the purpose of it?

43 What is Reflection in .NET?

44 What is the managed and unmanaged code in .net?

45 What are Namespaces?

46 What are the access-specifiers available in c#?

47 Advantage of ADO.Net?

48 Difference between OLEDB Provider and SqlClient ?

49 Differences between dataset.clone and dataset.copy?

50 In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice?

51 What is Remoting?

52 What’s the difference between System.String and System.StringBuilder classes?

53 What’s a delegate?

54 What’s an interface class?

55 What is the transport protocol you use to call a Web service ?

56 What’s wrong with a line like this? DateTime.Parse(myString);

57 What are PDBs? Where must they be located for debugging to work?

58 What is cyclomatic complexity and why is it important?

59 Write a standard lock() plus “double check” to create a critical section around a variable access.

60 What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

61 What does this do? gacutil /l | find /i "Corillian"

62 What does this do? sn -t foo.dll

63 What ports must be open for DCOM over a firewall? What is the purpose of Port 135?

64 Contrast OOP and SOA. What are tenets of each?

65 How does the XmlSerializer work? What ACL permissions does a process using it require?

66 Why is catch(Exception) almost always a bad idea?

67 What is the difference between Debug.Write and Trace.Write? When should each be used?

68 What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?

69 Does JITting occur per-assembly or per-method? How does this affect the working set?

70 Contrast the use of an abstract base class against an interface?

71 What is the difference between a.Equals(b) and a == b?

72 In the context of a comparison, what is object identity versus object equivalence?

73 How would one do a deep copy in .NET?

74 Explain current thinking around IClonable.

75 What is boxing?

76 Is string a value type or a reference type?

77 What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?

78 Why are out parameters a bad idea in .NET? Are they?

79 Can attributes be placed on specific parameters to a method? Why is this useful?

80 Juxtapose the use of override with new. What is shadowing?

81 Explain the use of virtual, sealed, override, and abstract.

82 Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d

83 Explain the differences between public, protected, private and internal.

84 What benefit do you get from using a Primary Interop Assembly (PIA)?

85 By what mechanism does NUnit know what methods to test?

86 What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}

87 What is the difference between typeof(foo) and myFoo.GetType()?

88 Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?

89 What is this? Can this be used within a static method?

csharp interview questions, c# faqs

C # Programmer Interviewing Questions :

•How many levels of compilations
happen in .NET languages? What is the first level of compilation?

•Can ASP.NET web pages be programmed in C#?

• Describe object pooling?

•What is indexer? Where is it used?

•What are multiple inheritances? And, how to implement it in C#?

•Can you explain what Common Language Runtime (CLR) is?

•Within a specific code block how can you enforce arithmetic overflow check?

•What is a shadow and an override? What is the difference between the two of them? • How do you explain Dynamic Link Library (DLL)?

•Can we use polymorphisms and i
nheritance in C# programming? If yes, in what way can they be used?

•What is a hashtable? How can you objects in a hashtable?

•What are BufferedStream, MemoryStream and FileStream?


•Can Stream objects be initialized?

•How will you define encapsulation? Can you give me some examples.

•Which class is used to read or write data to the memory?

• What is the difference between a client code and server code?

•In C # programming is it possible to add 'unmanaged code' that may not be necessarily CLS compliant?


•In C#, is it possible to inherit multiple interface?


• Explain Just In Time Compiler? What does JIT compiler do?

•How are parent classes referred in C#?

•How would you explain serialization? What are the advantages of serialization?

•Define abstraction?

•What is a shared assembly?

•How can you explain private assembly?

•Can pointers be used in C #?

•How can you explain XML schema?

•Can you explain what is method definition?

•Define Intermediate Language (IL). What has a similar concept to IL?

•What is a Thread? Can you describe the uses of thread in C# programming?


•How do we create and manage files in C#?

•Are 'object' and 'string', predefined reference types in C#?

•What is the method used to start a thread?

• How do we generate XML documents in C# programs?

•Give reasons why assemblies can't be loaded side by side.

•How can we load assembly in a running process?

•Explain what is multi level hierarchy?

• What happens if the XML comments are not well formed?

•What are constructors? How many types of constructors does C# support?

•Can constructors be static?

•What does "death of diamond" mean?

•How to use arraylist in C#? Can you provide us with examples?

ASP.NET Interview questions and answers for fragmentation chaching

What is fragment caching?
Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.

What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.

What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control’s class declaration to enable fragment caching.

What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.

VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).

If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can’t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.

When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect.
If the Web form’s cache duration is longer than the user control’s, both the Web form response and the user control response will expire using the Web form setting.

C# interview questions and answers on strings

What is the difference between string keyword and System.String class?
string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

Are string objects mutable or immutable?
String objects are immutable.

What do you mean by String objects are immutable?
String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "First String ";
string s2 = "Second String";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;

System.Console.WriteLine(s1);
// Output: First String Second String

What will be the output of the following code?
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);

The output of the above code is "Hello" and not "Hello C#". This is bcos, if you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

What is a verbatim string literal and why do we use it?
The "@" symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:

string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg

string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/

string DoubleQuotesString = @"My Name is ""Vankat.""";
//Output: My Name is "Vankat." 


Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);
The above code will compile, but at runtime System.NullReferenceException will be thrown.

How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;

What is the difference between System.Text.StringBuilder and System.String?
1.
Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.

How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "One";
int i = 0;
if(int.TryParse(str,out i))
{
Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
Console.WriteLine("string does not contain Integer");
}

What is the difference between int.Parse and int.TryParse methods?
Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

c# boxing and unboxing interview question and answers

What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing

Unboxing - Converting a reference type to a value typpe is called unboxing. An example is shown below.
obj = 101;
i = (int)obj; // Unboxing

Is boxing an implicit conversion?
Yes, boxing happens implicitly.

Is unboxing an implicit conversion?
No, unboxing is an explicit conversion.

What happens during the process of boxing?
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.

C# interview questions and answers on value types

What are the 2 types of data types available in C#?
1.
Value Types
2. Reference Types

If you define a user defined data type by using the struct keyword, Is it a a value type or reference type?
Value Type

If you define a user defined data type by using the class keyword, Is it a a value type or reference type?
Reference type

Are Value types sealed?
Yes, Value types are sealed.

What is the base class from which all value types are derived?
System.ValueType

Give examples for value types?
Enum
Struct

Give examples for reference types?
Class
Delegate
Array
Interface

What are the differences between value types and reference types?
1.
Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.

c# datatypes interview question and answers

What are the 3 types of comments in C#?
1. Single Line Comments. You define single line comments with // as shown below.
//This is an example for single line comment
2. Multi line comments. You define multi line comments with /* */ as shown below.
/*This is an example for
Multi Line comments*/
3. XML Comments. You define XML comments with /// as shown below.
///This is an example for defining XML comments.

Is C# a strongly-typed language?
Yes

What are the 2 broad classifications of data types available in C#?
1.
Built in data types.
2. User defined data types.

Give some examples for built in datatypes in C#?
1.
int
2. float
3. bool

How do you create user defined data types in C#?
You use the struct, class, interface, and enum constructs to create your own custom types. The .NET Framework class library itself is a collection of custom types provided by Microsoft that you can use in your own applications.

Basic c# interview question and answers

What do you mean by saying a "class is a reference type"?
A class is a reference type means when an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.

What do you mean by saying a "struct is a value type"?
A struct is a value type mean when a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.

When do you generally use a class over a struct?
A class is used to model more complex behavior, or data that is intended to be modified after a class object is created. A struct is best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

List the 5 different access modifiers in C#?
1.
public
2. protected
3. internal
4. protected internal
5. private

If you donot specify an access modifier for a method, what is the default access modifier?
private

Classes and structs support inheritance. Is this statement true or false?
False, Only classes support inheritance. structs donot support inheritance.

If a class derives from another class, will the derived class automatically contain all the public, protected, and internal members of the base class?
Yes, the derived class will automatically contain all the public, protected, and internal members of the base class except its constructors and destructors.

Can you create an instance for an abstract class?
No, you cannot create an instance for an abstract class.

How do you prevent a class from being inherited by another class?
Use the sealed keyword to prevent a class from being inherited by another class.

Classes and structs can be declared as static, Is this statement true or false?
False, only classes can be declared as static and not structs.

Can you create an instance of a static class?
No, you cannot create an instance of a static class.

Can a static class contain non static members?
No, a static class can contain only static members.

C# interview questions and answers on structs

Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"

Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No

Can you instantiate a struct without using a new operator in C#?
Yes, you can instantiate a struct without using a new operator

Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.

Can a struct inherit from an interface in C#?
Yes

Are structs value types or reference types?
Structs are value types.

What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.

C# interview questions and answers on inheritance

What are the 4 pillars of any object oriented programming language?
1.
Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism

Do structs support inheritance?
No, structs do not support inheritance, but they can implement interfaces.

What is the main advantage of using inheritance?
Code reuse

Is the following code legal?
class ChildClass : ParentClassA, ParentClassB
{
}

No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.

What will be the output of the following code?
using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.

Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.

C# interview questions and answers for abstract class members

What is an abstract class?
An abstract class is an incomplete class and must be implemented in a derived class.

Can you create an instance of an abstract class?
No, abstract classes are incomplete and you cannot create an instance of an abstract class.

What is a sealed class?
A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}

What are abstract methods?
Abstract methods are methods that only the declaration of the method and no implementation.

Will the following code compile?
using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a compile time error stating "Customer.Test() cannot declare a body because it is marked abstract"

Is the following code legal?
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}

No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"

How can you force derived classes to provide new method implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}

public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}

public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation.
}
}

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

Can a sealed class be used as a base class?
No, sealed class cannot be used as a base class. A compile time error will be generated.

Will the following code compile?
public abstract sealed class Test
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.

C# interview questions and answers for polymormhism

Explain polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];

DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();

foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}

When can a derived class override a base class member?
A derived class can override a base class member only if the base class member is declared as virtual or abstract.

What is the difference between a virtual method and an abstract method?
A virtual method must have a body where as an abstract method should not have a body.

Can fields inside a class be virtual?
No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.

Give an example to show for hiding base class methods?
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}

Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}

Why should ToString() method get over ridden

All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below.

using System;
public class MainClass
{
  public static void Main()
  {
   int Number = 10;
   Console.WriteLine(Number.ToString());
  }
}

In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method.

If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class.

using System;
public class Customer
{
 public string FirstName;
 public string LastName;
}
public class MainClass
{
 public static void Main()
 {
  Customer C = new Customer();
  C.FirstName = "David";
  C.LastName = "Boon";
  Console.WriteLine(C.ToString());
 }
}

The code sample below shows how to override the ToString() method in a class, that would give the output you want.


using System;
public class Customer
{
  public string FirstName;
  public string LastName;

  public override string ToString()
  {
    return LastName + ", " + FirstName;
  }
}
public class MainClass
{
  public static void Main()
  {
    Customer C = new Customer();
    C.FirstName = "David";
    C.LastName = "Boon";
    Console.WriteLine(C.ToString());
  }
}

Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method.

C# interview questions and answers

What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.

Private
The type or member can only be accessed by code in the same class or struct.

Protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

Internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

What are Access Modifiers used for?
Access Modifiers are used to control the accessibilty of types and members with in the types.

Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.

Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
using System;
internal class InternalBaseClass
{
   public void Print()
   {
      Console.WriteLine("I am a Base Class Method");
   }
}
public class PublicDerivedClass : InternalBaseClass
{
   public static void Main()
   {
      Console.WriteLine("I am a Public Derived Class Method");
   }
}


When you compile the above code an error will be generated stating "Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass".To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.


Is the following code legal?

using System;
private class Test
{
   public static void Main()
   {
   }
}


No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"

Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support inheritance.

Can the accessibility of a type member be greater than the accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.

Can destructors have access modifiers?
No, destructors cannot have access modifiers.

What does protected internal access modifier mean?
The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

What is the default access modifier for a class,struct and an interface declared directly with a namespace?
internal

Will the following code compile?

using System;
interface IExampleInterface
{
   public void Save();
}

No, you cannot specify access modifer for an interface member. Interface members are always public.

Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.

C# interview questions and answers on Fields

What are the 2 broad classifications of fields in C#?
1. Instance fields
2. Static fields

What are instance fields in C#?
Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object.

What is a static field?
A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.

Will the following code compile?

using System;
class Area
{
   public static double PI = 3.14;
}
class MainClass
{
   public static void Main()
   {
      Area A = new Area();
      Console.WriteLine(A.PI);
   }
}
No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields can only be accessed using the name of the class and not the instance of the class. The above sample program is rewritten as shown below.

using System;
class Area
{
   public static double PI = 3.14;
}
class MainClass
{
   public static void Main()
   {
      Console.WriteLine(Area.PI);
   }
}

Can you declare a field readonly?
Yes, a field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. An example is shown below.

using System;
class Area
{
   public readonly double PI = 3.14;
}
class MainClass
{
   public static void Main()
   {
      Area A = new Area();
      Console.WriteLine(A.PI);
   }
}

Will the following code compile?

using System;
class Area
{
   public readonly double PI = 3.14;
}
class MainClass
{
   public static void Main()
   {
      Area A = new Area();
      A.PI = 3.15;
      Console.WriteLine(A.PI);
   }
}

No, PI is readonly. You can only read the value of PI in the Main() method. You cannot assign any value to PI.

What is wrong with the sample program below?

using System;
class Area
{
   public const double PI = 3.14;
   static Area()
   {
      Area.PI = 3.15;
   }
}
class MainClass
{
   public static void Main()
   {
      Console.WriteLine(Area.PI);
   }
}
You cannot assign a value to the constant PI field.

What is the difference between a constant and a static readonly field?
A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.

C# interview questions and answers on Arrays

What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below

1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

int[] IntegerArray; // not int IntegerArray[];

2.
Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.

int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array

What are the 3 different types of arrays that we have in C#?
1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays

Are arrays in C# value types or reference types?
Reference types.

What is the base class for all arrays in C#?
System.Array

How do you sort an array in C#?
The Sort static method of the Array class can be used to sort array items.

Give an example to print the numbers in the array in descending order?
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}

What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}

Give an example to show how to copy one array into another array?
We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}

C# interview questions and answers on Constants

What are constants in C#?
Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.

using System;
class Circle
{
   public const double PI = 3.14;
   public Circle()
   {
      //Error : You can only assign a value to a constant field at the time of declaration
      //PI = 3.15;
   }
}
class MainClass
{
   public static void Main()
   {
      Console.WriteLine(Circle.PI);
   }
}

Can you declare a class or a struct as constant?
No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Does C# support const methods, properties, or events?
No, C# does not support const methods, properties, or events.

Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the example below, the constant field PI is always 3.14, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, PI), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference.

using System;
class Circle
{
   public const double PI = 3.14;
}

How do you access a constant field declared in a class?
Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. In the example below constant field PI can be accessed in the Main method using the class name and not the instance of the class. Trying to access a constant field using a class instance will generate a compile time error.

using System;
class Circle
{
   public const double PI = 3.14;
}
class MainClass
{
   public static void Main()
   {
      Console.WriteLine(Circle.PI);
      Circle C = new Circle();
      // Error : PI cannot be accessed using an instance
      // Console.WriteLine(C.PI);
   }
}

C# interview questions and answers on Properties

What are Properties in C#. Explain with an example?
Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.

The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.


using System;
class Customer
{
   // Private fileds not accessible outside the class.
   private string _firstName = string.Empty;
   private string _lastName = string.Empty;
   private string _coutry = string.Empty;

   // public FirstName property exposes _firstName variable
   public string FirstName
   {
      get
      {
         return _firstName;
      }
      set
      {
         _firstName = value;
      }
   }
   // public LastName property exposes _lastName variable
   public string LastName
   {
      get
      {
         return _lastName;
      }
      set
      {
         _lastName = value;
      }
   }
   // FullName property is readonly and computes customer full name.
   public string FullName
   {
      get
      {
         return _lastName + ", " + _firstName;
      }
   }
   //Country Property is Write Only
   public string Country
   {
      set
      {
         _coutry = value;
      }
   }

}
class MainClass
{
   public static void Main()
   {
      Customer CustomerObject = new Customer();
      //This line will call the set accessor of FirstName Property
      CustomerObject.FirstName = "David";
      //This line will call the set accessor of LastName Property
      CustomerObject.LastName = "Boon";
      //This line will call the get accessor of FullName Property
      Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
   }
}

Explain the 3 types of properties in C# with an example?
1. Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2. Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.

What are the advantages of properties in C#?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value of other fields.

What is a static property. Give an example?
A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.

using System;
class Circle
{
   private static double _pi = 3.14;
   public static double PI
   {
      get
      {
         return _pi;
      }
   }
}
class MainClass
{
   public static void Main()
   {
      Console.WriteLine(Circle.PI);
   }
}

What is a virtual property. Give an example?
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.


using System;
class Customer
{
   private string _firstName = string.Empty;
   private string _lastName = string.Empty;

   public string FirstName
   {
      get
      {
         return _firstName;
      }
      set
      {
         _firstName = value;
      }
   }
   public string LastName
   {
      get
      {
         return _lastName;
      }
      set
      {
         _lastName = value;
      }
   }
   // FullName is virtual
   public virtual string FullName
   {
      get
      {
         return _lastName + ", " + _firstName;
      }
   }
}
class BankCustomer : Customer
{
   // Overiding the FullName virtual property derived from customer class
   public override string FullName
   {
      get
      {
         return "Mr. " + FirstName + " " + LastName;
      }
   }
}
class MainClass
{
   public static void Main()
   {
      BankCustomer BankCustomerObject = new BankCustomer();
      BankCustomerObject.FirstName = "David";
      BankCustomerObject.LastName = "Boon";
      Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
   }
}

What is an abstract property. Give an example?
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.


using System;
abstract class Customer
{
   private string _firstName = string.Empty;
   private string _lastName = string.Empty;

   public string FirstName
   {
      get
      {
         return _firstName;
      }
      set
      {
         _firstName = value;
      }
   }
   public string LastName
   {
      get
      {
         return _lastName;
      }
      set
      {
         _lastName = value;
      }
   }
   // FullName is abstract
   public abstract string FullName
   {
      get;
   }
}
class BankCustomer : Customer
{
   // Overiding the FullName abstract property derived from customer class
   public override string FullName
   {
      get
      {
         return "Mr. " + FirstName + " " + LastName;
      }
   }
}
class MainClass
{
   public static void Main()
   {
      BankCustomer BankCustomerObject = new BankCustomer();
      BankCustomerObject.FirstName = "David";
      BankCustomerObject.LastName = "Boon";
      Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
   }
}

Can you use virtual, override or abstract keywords on an accessor of a static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.