C# Interview Questions

Question: How can we access parent class variable in child class.
We can use base.PropertyName.

Question: Explain CTS.
Common Type System (CTS) is a standard that specifies how type definitions and specific values of types are represented in computer memory. It is intended to allow programs written in different programming languages to easily share information.

Question: What is parent class of System.Int32
System.ValueType

Question: Explain overloading and overriding.
Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments

void Add(int a,int b)
{
return a+b;
}
void Add(int a, float b,int c)
{
return a+b+c;
}

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class BaseClass
{
public virtual int Add(int a,int b)
{
    return a+b;
}
}

class ChildClass : BaseClass
{
    public override int Add(int a, int b)
{
    return a+b+100;
}
}

Question: Difference between class and object.

Class
It is a data type that contains the programming logic.
Class is visible in the source code and resides in hard disk.
Class is like a template or blueprint of the object. It implements reusability, encapsulation, inheritance

Object
It is a chunk of memory that implements the class logic.
Object is in the RAM and not visible in source code.
It is the real world implementation of the class. Each object has its own copy of data.

Question: Difference between out and ref.

Ref
The parameter or argument must be initialized first before it is passed to ref.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.
It is not compulsory to initialize a parameter value before using it in a calling method.
When we use REF, data can be passed bi-directionally.

Out
It is not compulsory to initialize a parameter or argument before it is passed to an out.
A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
A parameter value must be initialized within the calling method before its use.
When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).

Question: What is yield keyword?
When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.

Question: Difference between thrown and throw ex.
throw ex resets the stack trace (so your errors would appear to originate from HandleException)
throw doesn’t the original offender would be preserved.

Question: Difference between var and dynamic.
Or
Why dynamic datatype introduce?

Var
1: It can store any kind of value but it is mandatory to initialize at time of declaration.
var obj=10;
2: var is type safety.
3: Can’t initialize with null
4: Can’t pass as method parameter and cannot have return type as well
5: Casting is not required.

Dynamic
1: It can store any kind of value.
dynamic obj;
2: dynamic is not type safety
3: dynamic is initialize with null
4: dynamic type can be passed as method parameter and also can return dynamic type.

public dynamic Method2(dynamic param)
        {
            dynamic objResponse = param;
            return objResponse;
        }

5: Casting is not require but you need to know the property and methods related to stored type

Question: When to use Abstract Class over Interface.

Interface: When you do not know anything about the implementation.
You want to take advantage of multiple inheritances.
When you want to take advantage of decouple architecture.
Abstract Class: When you partial know about the implementation.
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields or require access modifiers other than public (such as protected and private).

Question: Does interface has property?
Yes, Interface does have property.

Question: Why we use private constructor.
If a class has a private constructor then it can’t be instantiated. If you have a class that should only be created through factory methods or if you have overloads of the constructor and some of them should only be used by the other constructors.

Question: Difference between IQueryable and IEnumerable.

IEnumerable represents a forward-only cursor of T. .NET 3.5 added extension methods that included the LINQ standard query operators like Where and First, with any operators that require predicates or anonymous functions taking Func.

IQueryable implements the same LINQ standard query operators, but accepts Expression<Func> for predicates and anonymous functions. Expression is a compiled expression tree, a broken-up version of the method (“half-compiled” if you will) that can be parsed by the queryable’s provider and used accordingly.

Question: How to prevent from inheritance.
By using sealed keyword in order to prevent a class from being inherited.

Question: Type of class.
There are four type of class.
1: Abstract Class
2: Partial Class
3: Sealed Class
4: Static Class

Question: What is generic?
Generics is a technique that enriches your programs. It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.

Question: Difference between string and stringbuilder.
String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory.

StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating new instance for every time.it will update string at one place in memory doesn’t create new space in memory.

Question: Give a real example where you use queues?
Queue represents FIFO. Last week I visit ICICI bank where I got my token and wait for my turn. If I have to make this kind of application the I will use queue for it.

Question: Explain extension method?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

static class MyExtentionClass
{
public static int ConvertInt(this string s)
{
    retrun Int32.Parse(s);
}
}

class Program
{
Static void Main(string[] args)
{
    Int Num = “1234”.ConvertInt();
    Console.ReadLine();
}
}

Question: What is garbage collection?
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs. The System.GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously.

Question: How boxing and unboxing works.
Boxing is the process of converting a value type to type object.

Int i=123;
Object obj =1;

The vise-versa of boxing is unboxing.

obj = 123;
I = (int)o;

Question: Can we create static method in abstract class?
Yes, we can create static method in abstract class.

Question: Can we create static abstract method?
No, we cannot create static abstract method.

Question: Explain delegate, func, action and predicate.
Delegate is a function pointer. Delegate allows the programmer to encapsulate a reference to a method inside delegate object.

Func is a delegate but difference is the way to declare. Func has an always return type.
Action is used when we do not have return type.
Predicate is used when we do have bool return type.

Question: How linq works?

Expression trees: These are representations of code as data. For instance, an expression tree could represent the notion of “take a string parameter, call the Length property on it, and return the result”. The fact that these exist as data rather than as compiled code means that LINQ providers such as LINQ to SQL can analyze them and convert them into SQL.
Lambda expressions: These are expressions like this:

x => x * 2
(int x, int y) => x * y
() => { Console.WriteLine("Block"); Console.WriteLine("Lambda"); }

Lambda expressions are converted either into delegates or expression trees.

Anonymous types: These are expressions like this:

new { X=10, Y=20 }

These are still statically typed, it’s just the compiler generates an immutable type for you with properties X and Y. These are usually used with var which allows the type of a local variable to be inferred from its initialization expression.

Query expressions: These are expressions like this:

from person in people
where person.Age < 18
select person.Name

These are translated by the C# compiler into “normal” C# 3.0 (i.e. a form which doesn’t use query expressions). Overload resolution etc is applied afterwards, which is absolutely key to being able to use the same query syntax with multiple data types, without the compiler having any knowledge of types such as Queryable. The above expression would be translated into:

people.Where(person => person.Age  person.Name)

Extension methods: These are static methods which can be used as if they were instance methods of the type of the first parameter. For example, an extension method like this:

public static int CountAsciiDigits(this string text)
{
    return text.Count(letter => letter >= '0' && letter <= '9');
}

can then be used like this:

string foo = "123abc456";
int count = foo.CountAsciiDigits();

Note that the implementation of CountAsciiDigits uses another extension method, Enumerable.Count().

Question: Is there any difference between foreach vs linq as performance point of view.
LINQ takes a little bit more time because you are iterating over all of the items. But in your other two loops you are breaking the loop as soon as you find a match. Try using FirstOrDefault instead of Where and you should get the same (or similar) result.

people.FirstOrDefault(p => p.Name == name);

Question: How to join 2 tables in linq.

var innerJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID
    select new { ProductName = prod.Name, Category = category.Name };

Question: Is it better to keep configurations in configuration file or database.
It depends on requirement.

Question: What is TPL.
The Task Parallel Library (TPL) is based on the concept of a task, which represents an asynchronous operation. In some ways, a task resembles a thread or ThreadPool work item, but at a higher level of abstraction. The term task parallelism refers to one or more independent tasks running concurrently.

Tags: