Below is top C# interview question and answers with examples for freshers and intermediate developers.
What is C#?
C# is a general-purpose, object-oriented programming language developed by Microsoft around 2000. It is strongly type and it encompasses imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines.
What are the four Pillars of Object Oriented Programming?
Below is the main Pillars of Object Oriented Programming.
- Inheritance
- Encapsulation
- Abstraction
- Polyporphism
What is Inheritance?
Inheritance is when an object or class is based on another object or class, using the same implementation or specifying implementation to maintain the same behaviour.
What is Encapsulation?
Encapsulation is a packing of data and functions into a single component. It prevents access to implementation details. Class is an example of encapsulation
What is Abstraction?
Abstraction refers to represent essential data without including the background details. Abstractions can be achieved by means of access specifiers
What is Polyporphism?
Polymorphism means one object behaving as multiple forms. There is compile time and runtime polyporphism.
In compile time polymorphism, we can declare methods with same name but different parameters and it is called as method overloading.
Runtime polymorphism can be achieved by method overriding.
What is Class in C#?
A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type.
What is Object in C#?
An object is basically a block of memory that has been allocated and configured according to the class or struct (blueprint).
Objects are also called instances, and they can be stored in either a named variable or
in an array or collection.
Client code is the code that uses these variables to call the methods and access the public properties of the object.
In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically.
What is Value Type and Reference Type?
Value Type A value type variable holds data value within own memory space that means this variable contains their value directly. Data of value type stored in Stack memory. Below data types are value type.
- bool
- byte
- char
- decimal
- double
- enum
- float
- int
- long
- sbyte
- short
- struct
- uint
- ulong
- ushort
- class
- interface
- delegate
- array
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.
Explain the passing parameters by value and passing parameters by reference with an example
Passing by Value When you pass a value type variable from one method to another method, the system creates a separate copy of a variable in another method, so that if value got changed in the one method won't affect on the variable in another method.
namespace ConsoleApplication1 { class Program { public static void Main() { int A = 10; Console.WriteLine("Value of A before passing to method = " + A); MyFunction(A); Console.WriteLine("Value of A after passing to method = " + A); Console.ReadKey(); } public static int MyFunction(int number) { return number = number + 5; } } } /* OUTPUT: Value of A before passing to method = 10 Value of A after passing to method = 10 */
Passing by Reference When you pass a reference type variable from one method to another, it doesn't create a new copy; instead, it passes the address of the variable. If we change the value of the variable in a method, it will also be reflected in the calling method.
namespace ConsoleApplication1 { class Program { public static void Main() { int A = 10; Console.WriteLine("Value of A before passing to method = " + A); MyFunction(ref A); Console.WriteLine("Value of A after passing to method = " + A); Console.ReadKey(); } public static void MyFunction(ref int number) { return number = number + 5; } } } /* OUTPUT: Value of A before passing to method = 10 Value of A after passing to method = 15 */
What is namespace in C#?
A namespace is used to organize your code logically. A namespace in collection of classes, interface, structs, enums, delegates and other namespaces.
What is difference between ref and out parameter or ref and out keywords?
The ref and out keywords are used to pass the parameter to the function. Both Ref and out keywords are used to pass parameter by reference. ref: The ref keyword is used to pass parameter as reference. If value of parameter is changed in called method then parameters changed value is also gets reflected in calling method. The parameter must be initialized in calling method before it passed to called method. out: The out keyword is also used to pass parameter as reference. Here, initialization of parameter is not necessary in calling method before passing parameter to called method. But, initialization is compulsory in called method before returning back to called method. Ex.
namespace ConsoleApplication1 { class Program { static void Main(string[] args) // calling method { int number1 = 10; // must be initialized before passing to Method1 int number2; // it can be optional or can be initialized Method1(ref number1); Console.WriteLine(number1); Method2(out number2); Console.WriteLine(number2); Console.ReadKey(); } static void Method1(ref int number1) // called method { number1 = 11; } static void Method2(out int number2) // called method { number2 = 12; // must be initialized } } } /* OUTPUT: 11 12 */
Note:
1) A data type of value type or reference type can be pass to method by ref keyword. But, if a value type is passed using ref keyword then boxing does not occurs.
2) Properties cannot be passed using ref or out keyword as they are implemented as function internally.
What is boxing and unboxing?
The process of converting value type to reference type is boxing and reference type to value type in unboxing. Boxing and unboxing is not a data type conversion. Boxing is basically storing a value type as an object in heap and unboxing is reading the value from the object. Ex.
namespace ConsoleApplication1 { class Program { static void Main(string[] args) // calling method { int a = 10; object obj = (object)a; // Boxing int b = (int)obj; // unboxing Console.ReadKey(); } } }
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.
What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.
What are the 2 kinds of data type conversions in C#?
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes. Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.
What is the difference between an implicit conversion and an explicit conversion?
Explicit conversions require a cast operator where as an implicit converstion is done automatically.
Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.
Will the following code compile?
double d = 9999.11;
int i = d;
No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.
double d = 9999.11;
int i = (int)d; //Cast double to int.
If you want to convert a base type to a derived type, what type of conversion do you use?
Explicit conversion as shown below. Consider Vehicle as base class and Car as derived class.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;
// Explicit conversion is required to cast back to derived type.
The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.
If casting fails what type of exception is thrown?
InvalidCastException
What are the 2 types of data types available in C#?
Value Types
Reference Types
Are Value types sealed?
Yes, Value types are sealed.
What is the base class from which all value types are derived?
System.ValueType
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.
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.
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.