Csharp
[C#]¶
What is the difference between "continue" and "break" statements in C#?
What is the difference between a struct and a class in C#?
Filter out the first 3 even numbers from the list using LINQ
How is Exception Handling implemented in C#?
Why to use “finally” block in C#?
What are nullable types in C#?
What are dynamic type variables in C#?
Can "this" be used within a static method?
What is Managed or Unmanaged Code?
What are reference types in C#?
What is the difference between string and StringBuilder in c#?
In how many ways you can pass parameters to a method?
Can you return multiple values from a function in C#?
What are the different types of classes in C#?
Why can't you specify the accessibility modifier for methods inside the interface?
Can multiple catch blocks be executed?
What you understand by Value types and Reference types in C#.Net?
What is the difference between ref and out keywords?
What is the difference between Equality Operator (==) and Equals() Method in C#?
What is an anonymous function in C#?
What is lambda expressions in C#?
What is the difference between Interface and Abstract Class?
What is the output of the program below? Explain your answer.
Given an array of ints, write a C# method to total all the values that are even numbers.
What is the difference between constant and readonly in c#?
What are the uses of “using” in C#
What is the use of Null Coalescing Operator (??) in C#?
What is scope of a Internal member variable of a C# class?
What is difference between Throw Exception and Throw Clause?
How encapsulation is implemented in C#?
What is difference between constants and readonly?
What is the difference between dynamic type variables and object type variables?
What is extension method in C# and how to use them?
What is delegates in C# and uses of delegates?
What is the difference between overloading and overriding?
Explain Code compilation in C#
What is the difference between Virtual method and Abstract method?
What's the difference between StackOverflowError and OutOfMemoryError?
What is difference between late binding and early binding in C#?
What are the different ways a method can be overloaded?
What is the difference between dispose and finalize methods in c#?
What is marshalling and why do we need it?
Describe the accessibility modifier "protected internal".
What are the differences between a multidimensional array and an array of arrays in C#?
What is scope of a Protected Internal member variable of a C# class?
Can you create a function in C# which can accept varying number of arguments?
Is operator overloading supported in C#?
What is the use of conditional preprocessor directive in C#?
What is the difference between System.ApplicationException class and System.SystemException class?
Can we have only “try” block without “catch” block in C#?
In try block if we add return statement whether finally block is executed in C#?
What is the Constructor Chaining in C#?
What are the uses of delegates in C#?
Why to use lock statement in C#?
Can Multiple Inheritance implemented in C# ?
What is the output of the short program below? Explain your answer.
Is the comparison of time and null in the if statement below valid or not? Why or why not?
What is the output of the program below? Explain your answer.
What is the output of the program below?
When to use ArrayList over array[] in c#?
What is the "yield" keyword used for in C#?
What is an Object Pool in .Net?
What interface should your data structure implement to make the "Where" method work?
IEnumerable vs List - What to Use? How do they work?
Name difference between "is" and "as" operator in C#
What is the difference between Func
Explain the difference between Select and Where
Explain what is short-circuit evaluation in C#
List some different ways for equality check in .Net
What is multicast delegate in C#?
What is jagged array in C#.Net and when to prefer jagged arrays over multi-dimensional arrays?
Can you create sealed abstract class in C#?
What is deep or shallow copy concept in C#?
What is a preprocessor directives in C#?
Could you explain the difference between destructor, dispose and finalize method?
What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
What are the benefits of a Deferred Execution in LINQ?
What is the method MemberwiseClone() doing?
What is the difference between lambdas and delegates?
What are the differences between IEnumerable and IQueryable?
Could you explain the difference between Func vs. Action vs. Predicate?
Explain what is weak reference in C#?
Explain the difference between IQueryable, ICollection, IList & IDictionary interfaces?
in C#, when should we use abstract classes instead of interfaces with extension methods?
Can you add extension methods to an existing static class?
Implement the "Where" method in C#
What is the “volatile” keyword used for?
Calculate the circumference of the circle
What is the use of static constructors?
What is C#?¶
C# is the programming language for writing Microsoft .NET applications. C# provides the rapid application development found in Visual Basic with the power of C++. Its syntax is similar to C++ syntax and meets 100% of the requirements of OOPs like the following:
- Abstraction
- Encapsulation
- Polymorphism
- Inheritance
Source¶
What is the difference between "continue" and "break" statements in C#?¶
- using break statement, you can jump out of a loop
- using continue statement, you can jump over one iteration and then resume your loop execution
Source¶
What are property Accessors?¶
The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property, the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a read-only field. By the get accessor we can access the value of the private field, in other words it returns a single value. A Get accessor specifies that we can access the value of a field publically.
Source¶
What is an Object?¶
According to MSDN, "a class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. 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".
Objects helps us to access the member of a class or struct either they can be fields, methods or properties, by using the dot.
Source¶
What is the difference between a struct and a class in C#?¶
Class and struct both are the user defined data type but have some major difference:
Struct
- The struct is value type in C# and it inherits from System.Value Type.
- Struct is usually used for smaller amounts of data.
- Struct can't be inherited to other type.
- A structure can't be abstract.
- No need to create object by new keyword.
- Do not have permission to create any default constructor.
Class
- The class is reference type in C# and it inherits from the System.Object Type.
- Classes are usually used for large amounts of data.
- Classes can be inherited to other class.
- A class can be abstract type.
- We can't use an object of a class with using new keyword.
- We can create a default constructor.
Source¶
Filter out the first 3 even numbers from the list using LINQ¶
Source¶
What is enum in C#?¶
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined. An enum is used to create numeric constants in .NET framework. All the members of enum are of enum type. Their must be a numeric value for each enum type.
Some points about enum
- Enums are enumerated data type in C#.
- Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
- Enumerations (enums) make your code much more readable and understandable.
- Enum values are fixed. Enum can be displayed as a string and processed as an integer.
- The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
- Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
- Enums are value types and are created on the stack and not on the heap.
Source¶
How is Exception Handling implemented in C#?¶
Exception handling is done using four keywords in C#:
- try – Contains a block of code for which an exception will be checked.
- catch – It is a program that catches an exception with the help of exception handler.
- finally – It is a block of code written to execute regardless whether an exception is caught or not.
- Throw – Throws an exception when a problem occurs.
Source¶
Why to use “finally” block in C#?¶
Finally block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last finally
block will be executed. So closing connection to database / releasing the file handlers can be kept in finally
block.
Source¶
What are nullable types in C#?¶
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32>
variable. Similarly, you can assign true, false, or null in a Nullable<bool>
variable.
Source¶
What are dynamic type variables in C#?¶
You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
Source¶
Can "this" be used within a static method?¶
We can't use this in static method because keyword this returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and call with the name of a class not by instance so we can't use this keyword in the body of static Methods, but in case of Extension Methods we can use it as the functions parameters.
Source¶
Define Property in C#?¶
Properties are members that provide a flexible mechanism to read, write or compute the values of private fields, in other words by the property we can access private fields. In other words we can say that a property is a return type function/method with one parameter or without a parameter. These are always public data members. It uses methods to access and assign values to private fields called accessors.
Source¶
What is Managed or Unmanaged Code?¶
- Managed Code - The code, which is developed in .NET framework is known as managed code. This code is directly executed by CLR with the help of managed code execution. Any language that is written in .NET Framework is managed code.
- Unmanaged Code - The code, which is developed outside .NET framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with the code of VB, ASP and COM are examples of unmanaged code.
Source¶
What are reference types in C#?¶
The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.
Source¶
What is namespace in C#?¶
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
Source¶
What is the difference between string and StringBuilder in c#?¶
String
- It's an immutable object that hold string value.
- Performance wise string is slow because its' create a new instance to override or change the previous value.
- String belongs to System namespace.
StringBuilder
- StringBuilder is a mutable object.
- Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.
- StringBuilder belongs to System.Text.Stringbuilder namespace.
Source¶
In how many ways you can pass parameters to a method?¶
There are three ways that parameters can be passed to a method:
- Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
- Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
- Output parameters − This method helps in returning more than one value.
Source¶
Can you return multiple values from a function in C#?¶
Yes! Using output parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function.
Source¶
What are partial classes?¶
A partial class is only use to splits the definition of a class in two or more classes in a same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you'll create an instance of this class so you can access all the methods from all source file with a same object. Partial classes can be create in the same namespace it's doesn't allowed to create a partial class in different namespace.
Source¶
What is an Abstract Class?¶
An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. An Abstract class should always be inherited. An instance of the class itself cannot be created. If we do not want any program to create an object of a class, then such classes can be made abstract.
Any method in the abstract class does not have implementations in the same class. But they must be implemented in the child class.
Source¶
What is Boxing and Unboxing?¶
Boxing and Unboxing both are used for type conversion but have some difference:
-
Boxing - Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.
-
Unboxing - Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by code.
The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of any type can be treated as an object.
Source¶
What are the different types of classes in C#?¶
The different types of class in C# are:
- Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
- Sealed class – It is a class which cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.
- Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.
- Static class – It is a class which does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.
Source¶
Why can't you specify the accessibility modifier for methods inside the interface?¶
In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are public.
Source¶
What are Custom Exceptions?¶
Sometimes there are some errors that need to be handeled as per user requirements. Custom exceptions are used for them and are used defined exceptions.
Source¶
Can multiple catch blocks be executed?¶
No, Multiple catch blocks can't be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.
Source¶
What is LINQ in C#?¶
LINQ stands for Language Integrated Query. LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T>
interface.
Source¶
What is Serialization?¶
Serialization means saving the state of your object to secondary memory, such as a file.
- Binary serialization (Save your object data into binary format).
- Soap Serialization (Save your object data into binary format; mainly used in network related communication).
- XmlSerialization (Save your object data into an XML file).
Source¶
What you understand by Value types and Reference types in C#.Net?¶
In C# data types can be of two types: Value Types and Reference Types. Value type variables contain their object (or data) directly. If we copy one value type variable to another then we are actually making a copy of the object for the second variable. Value Type member will located into Stack and reference member will located in Heap always.
Source¶
What are generics in C#?¶
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
Source¶
What is the difference between ref and out keywords?¶
- The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed
- The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method.
Source¶
What is the difference between Equality Operator (==) and Equals() Method in C#?¶
The == Operator (usually means the same as ReferenceEquals, could be overrided) compares the reference identity while the Equals() (virtual Equals()) method compares if two objects are equivalent.
Source¶
What is an anonymous function in C#?¶
An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.
There are two kinds of anonymous functions:
- Lambda Expressions
- Anonymous Methods
Consider:
// Original delegate syntax required
// initialization with a named method.
TestDelegate testDelA = new TestDelegate(M);
// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) {
Console.WriteLine(s);
};
// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => {
Console.WriteLine(x);
};
// Invoke the delegates.
testDelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
Source¶
What is lambda expressions in C#?¶
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
Source¶
What is the difference between Interface and Abstract Class?¶
There are some differences between Abstract Class and Interface which are listed below:
- A class can implement any number of interfaces but a subclass can at most use only one abstract class.
- An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract.
- An abstract class can declare or use any variables while an interface is not allowed to do so.
- In an abstract class all data member or functions are private by default while in interface all are public, we can't change them manually.
- In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don't need to use that.
- An abstract class can't be used for multiple inheritance while interface can be used as multiple inheritance.
- An abstract class use constructor while in an interface we don't have any type of constructor.
Source¶
What is Virtual Method in C#?¶
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived class. When a virtual method is invoked, the run-time type of the object is checked for an overriding member.
- By default, methods are non-virtual. We can't override a non-virtual method.
- We can't use the virtual modifier with the static, abstract, private or override modifiers.
Source¶
Refactor the code¶
The this
keyword is used to call other constructors, to initialize the class object. The following shows the implementation:
Source¶
What is the output of the program below? Explain your answer.¶
This program will output the number 10 ten times.
Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i
is stored, rather than the value itself. Therefore, after we exit the loop, the variable i
has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.
Source¶
Given an array of ints, write a C# method to total all the values that are even numbers.¶
static long TotalAllEvenNumbers(int[] intArray) {
return intArray.Where(i => i % 2 == 0).Sum(i => (long)i);
}
or
static long TotalAllEvenNumbers(int[] intArray) {
return (from i in intArray where i % 2 == 0 select (long)i).Sum();
}
Source¶
What is the difference between constant and readonly in c#?¶
Constant (const) and **Readonly **(readonly) both looks like same as per the uses but they have some differences:
-
**Constant **is known as "const" keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running.
-
Readonly is known as "readonly" keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call constructor with "new" keyword.
Source¶
What are the uses of “using” in C¶
The reason for the using statement is to ensure that the object is disposed (call IDisposable) as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
The .NET CLR converts:
to:
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
Source¶
What is the use of Null Coalescing Operator (??) in C#?¶
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise, it returns the right operand.
Source¶
What is scope of a Internal member variable of a C# class?¶
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
Source¶
Explain Anonymous type in C¶
Anonymous types allow us to create a new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.
Consider:
var anonymousData = new
{
ForeName = "Jignesh",
SurName = "Trivedi"
};
Console.WriteLine("First Name : " + anonymousData.ForeName);
Source¶
What is difference between Throw Exception and Throw Clause?¶
- The basic difference is that the Throw exception overwrites the stack trace and this makes it hard to find the original code line number that has thrown the exception.
- Throw retains the stack information and adds to the stack information in the exception that it is thrown.
Source¶
What is Reflection in C#.Net?¶
Reflection is the ability to query and interact with the type system in a dynamic way. Generally speaking Reflection allows you access to metadata about objects. For instance you can load a DLL and determine if it contains an implementation of an interface. You could use this to discover dll's that support functionality at runtime. Use could use this to extend an application without a recompilation and without having to restart it.
Source¶
How encapsulation is implemented in C#?¶
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member.
- Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
- Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
- Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance.
Source¶
What is difference between constants and readonly?¶
Constant variables are declared and initialized at compile time. The value can't be changed afterwards. Readonly is used only when we want to assign the value at run time.
Source¶
What is the difference between dynamic type variables and object type variables?¶
Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.
Source¶
What is extension method in C# and how to use them?¶
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.
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
Source¶
What is delegates in C# and uses of delegates?¶
C# delegates are same as pointers to functions, in C or C++. A delegate Object is a reference type variable that use to holds the reference to a method. The reference can be changed at runtime which is hold by an object of delegate, a delegate object can hold many functions reference which is also known as Invocation List that refers functions in a sequence FIFO, we can new functions ref in this list at run time by += operator and can remove by -= operator.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Source¶
What is sealed class in C#?¶
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.
Structs are also sealed. You cannot derive a class from a struct.
Source¶
What is the difference between overloading and overriding?¶
- Overloading is when you have multiple methods in the same scope, with the same name but different signatures.
//Overloading
public class test
{
public void getStuff(int id)
{}
public void getStuff(string name)
{}
}
- Overriding is a principle that allows you to change the functionality of a method in a child class.
//Overriding
public class test
{
public virtual void getStuff(int id)
{
//Get stuff default location
}
}
public class test2 : test
{
public override void getStuff(int id)
{
//base.getStuff(id);
//or - Get stuff new location
}
}
Source¶
Explain Code compilation in C¶
There are four steps in code compilation which include:
- Compiling the source code into Managed code by C# compiler.
- Combining the newly created code into assemblies.
- Loading the Common Language Runtime(CLR).
- Executing the assembly by CLR.
Source¶
What is the difference between Virtual method and Abstract method?¶
- A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using override keyword.
- An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.
Source¶
What is a Destructor in C#?¶
A Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.
Source¶
What's the difference between StackOverflowError and OutOfMemoryError?¶
- OutOfMemoryError is related to Heap. To avoid: Make sure un-necessary objects are available for GC
- StackOverflowError is related to stack. To avoid: Make sure method calls are ending (not in an infinite loop)
Source¶
What is difference between late binding and early binding in C#?¶
- In Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.
- Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn't allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that's way we says that Late Binding also known as Method overriding.
Source¶
What are the different ways a method can be overloaded?¶
Methods can be overloaded using different data types for parameter, different order of parameters, and different number of parameters.
Source¶
What is the difference between dispose and finalize methods in c#?¶
Finalizer and Dispose both are used for same task like to free unmanaged resources but have some differences see.
Finalize:
- Finalize used to free unmanaged resources those are not in use like files, database connections in application domain and more, held by an object before that object is destroyed.
- In the Internal process it is called by Garbage Collector and can't called manual by user code or any service.
- Finalize belongs to System.Object class.
- Implement it when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.
Dispose:
- Dispose is also used to free unmanaged resources those are not in use like files, database connections in Application domain at any time.
- Dispose explicitly it is called by manual user code.
- If we need to dispose method so must implement that class by IDisposable interface.
- It belongs to IDisposable interface.
- Implement this when you are writing a custom class that will be used by other users.
Source¶
What is marshalling and why do we need it?¶
Because different languages and environments have different calling conventions, different layout conventions, different sizes of primitives (cf. char in C# and char in C), different object creation/destruction conventions, and different design guidelines. You need a way to get the stuff out of managed land an into somewhere where unmanaged land can see and understand it and vice versa. That's what marshalling is for.
Source¶
Describe the accessibility modifier "protected internal".¶
Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.
Source¶
What are pointer types in C#?¶
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++.
Source¶
What are the differences between a multidimensional array and an array of arrays in C#?¶
- Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively.
- Multidimensional arrays have nicer syntax.
Source¶
What is scope of a Protected Internal member variable of a C# class?¶
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
Source¶
Can you create a function in C# which can accept varying number of arguments?¶
By using the params
keyword, you can specify a method parameter that takes a variable number of arguments. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration. The declared type of the params parameter must be a single-dimensional array.
public static void UseParams(params int[] list) {
for (int i = 0; i < list.Length; i++) {
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
public static void UseParams2(params object[] list) {
for (int i = 0; i < list.Length; i++) {
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
// usage
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");
Source¶
Is operator overloading supported in C#?¶
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list.
Source¶
What is the use of conditional preprocessor directive in C#?¶
You can use the #if
directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if
and the next directive.
Source¶
What is the difference between System.ApplicationException class and System.SystemException class?¶
- The
System.ApplicationException
class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. - The
System.SystemException
class is the base class for all predefined system exception.
Source¶
What is Indexer in C#?¶
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]). Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string.
Consider:
class IndexedNames {
private string[] namelist = new string[size];
public string this[int index] {
get {
string tmp;
if (index >= 0 && index <= size - 1) {
tmp = namelist[index];
} else {
tmp = "";
}
return (tmp);
}
set {
if (index >= 0 && index <= size - 1) {
namelist[index] = value;
}
}
}
}
Source¶
Can we have only “try” block without “catch” block in C#?¶
Yes we can have only try block without catch block but we have to have finally block.
Source¶
In try block if we add return statement whether finally block is executed in C#?¶
Yes. Finally block will still be executed in presence of return statement in try block.
Source¶
What is the Constructor Chaining in C#?¶
Constructor Chaining is an approach where a constructor calls another constructor in the same or base class. This is very handy when we have a class that defines multiple constructors.
Consider:
class Foo {
private int id;
private string name;
public Foo() : this(0, "") {
}
public Foo(int id) : this(id, "") {
}
public Foo(string name) : this(0, name) {
}
public Foo(int id, string name) {
this.id = id;
this.name = name;
}
}
Source¶
What are the uses of delegates in C#?¶
Below are the list of uses of delegates in C#:
- Callback Mechanism
- Asynchronous Processing
- Abstract and Encapsulate method
- Multicasting
Source¶
Why to use lock statement in C#?¶
Lock will make sure one thread will not intercept the other thread which is running the part of code. So lock statement will make the thread wait, block till the object is being released.
Source¶
Can Multiple Inheritance implemented in C# ?¶
In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, use interface.
Source¶
What is the output of the short program below? Explain your answer.¶
The output will be:
Although both variables are uninitialized, String
is a reference type and DateTime
is a value type. As a value type, an unitialized DateTime
variable is set to a default value of midnight of 1/1/1 (yup, that’s the year 1 A.D.), not null
.
Source¶
Is the comparison of time and null in the if statement below valid or not? Why or why not?¶
One might think that, since a DateTime
variable can never be null (it is automatically initialized to Jan 1, 0001), the compiler would complain when a DateTime
variable is compared to null
. However, due to type coercion, the compiler does allow it, which can potentially lead to headfakes and pull-out-your-hair bugs.
Specifically, the ==
operator will cast its operands to different allowable types in order to get a common type on both sides, which it can then compare. That is why something like this will give you the result you expect (as opposed to failing or behaving unexpectedly because the operands are of different types):
However, this can sometimes result in unexpected behavior, as is the case with the comparison of a DateTime
variable and null
. In such a case, both the DateTime
variable and the null
literal can be cast to Nullable<DateTime>
. Therefore it is legal to compare the two values, even though the result will always be false.
Source¶
What is the output of the program below? Explain your answer.¶
The answer to the first part of the question (i.e., the version of the code with await Task.Delay(5);
) is that the program will just output a blank line (not “Hello world!”). This is because result
will still be uninitialized when Console.WriteLine
is called.
Most procedural and object-oriented programmers expect a function to execute from beginning to end, or to a return
statement, before returning to the calling function. This is not the case with C# async
functions. They only execute up until the first await
statement, then return to the caller. The function called by await
(in this case Task.Delay
) is executed asynchronously, and the line after the await
statement isn’t signaled to execute until Task.Delay
completes (in 5 milliseconds). However, within that time, control has already returned to the caller, which executes the Console.WriteLine
statement on a string that hasn’t yet been initialized.
Calling await Task.Delay(5)
lets the current thread continue what it is doing, and if it’s done (pending any awaits), returns it to the thread pool. This is the primary benefit of the async/await mechanism. It allows the CLR to service more requests with less threads in the thread pool.
Asynchronous programming has become a lot more common, with the prevalence of devices which perform over-the-network service requests or database requests for many activities. C# has some excellent programming constructs which greatly ease the task of programming asynchronous methods, and a programmer who is aware of them will produce better programs.
With regard to the second part of the question, if await Task.Delay(5);
was replaced with Thread.Sleep(5)
, the program would output Hello world!
. An async
method without at least one await
statement in it operates just like a synchronous method; that is, it will execute from beginning to end, or until it encounters a return
statement. Calling Thread.Sleep()
simply blocks the currently running thread, so the Thread.Sleep(5)
call just adds 5 milliseconds to the execution time of the SaySomething()
method.
Source¶
What is the output of the program below?¶
TestValue : 10
The static constructor of a class is called before any instance of the class is created. The static constructor called here initializes the TestValue
variable first.
Source¶
When to use ArrayList over array[] in c#?¶
- Arrays are strongly typed, and work well as parameters. If you know the length of your collection and it is fixed, you should use an array.
- ArrayLists are not strongly typed, every Insertion or Retrial will need a cast to get back to your original type. If you need a method to take a list of a specific type, ArrayLists fall short because you could pass in an ArrayList containing any type. ArrayLists use a dynamically expanding array internally, so there is also a hit to expand the size of the internal array when it hits its capacity.
What you really want to use is a generic list like List
Source¶
What is the "yield" keyword used for in C#?¶
The function returns an object that implements the IEnumerable
interface. If a calling function starts foreach-ing over this object the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0.
Yield
has two great uses:
- It helps to provide custom iteration without creating temp collections.
- It helps to do stateful iteration.
The advantage of using yield
is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.
Source¶
What is an Object Pool in .Net?¶
Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool.
Source¶
What interface should your data structure implement to make the "Where" method work?¶
IEnumerable
Source¶
IEnumerable vs List - What to Use? How do they work?¶
IEnumerable
describes behavior, while List is an implementation of that behavior. When you use IEnumerable
, you give the compiler a chance to defer work until later, possibly optimizing along the way. If you use ToList()
you force the compiler to reify the results right away.
Whenever you "stacking" LINQ expressions, you should use IEnumerable
, because by only specifying the behavior gives LINQ a chance to defer evaluation and possibly optimize the program.
Source¶
Name difference between "is" and "as" operator in C¶
- The
is
operator checks if an object can be cast to a specific type.
- The
as
operator attempts to cast an object to a specific type, and returns null if it fails.
Source¶
What is the difference between Func and delegate?¶
The first is declaring a generic delegate variable and assigning a value to it, the second is just defining a delegate type. Both Func<string,string>
and delegate string convertMethod(string) would be capable of holding the same method definitions whether they be methods, anonymous methods, or lambda expressions.
Consider:
public static class Program
{
// you can define your own delegate for a nice meaningful name, but the
// generic delegates (Func, Action, Predicate) are all defined already
public delegate string ConvertedMethod(string value);
public static void Main()
{
// both work fine for taking methods, lambdas, etc.
Func<string, string> convertedMethod = s => s + ", Hello!";
ConvertedMethod convertedMethod2 = s => s + ", Hello!";
}
}
Source¶
Explain the difference between Select and Where¶
- Select is a projection, so what you get is the expression
x=> x.FirstName == "John"
evaluated for each element in ContextSet() on the server. i.e. lots of true/false values (the same number as your original list). If you look the select will return something likeIEnumerable<bool>
(because the type ofx=> x.FirstName == "John"
is a bool). UseSelect
when you want to keep all results, but change their type (project them). - Where filters the results, returning an enumerable of the original type (no projection). Use
Where
when you want to filter your results, keeping the original type
Source¶
Explain what is short-circuit evaluation in C¶
Short-circuit evaluation is a tricky method for evaluating logical operators AND and OR. In this method, the whole expression can be evaluated to true
or false
without evaluating all sub expressions.
Source¶
List some different ways for equality check in .Net¶
- The ReferenceEquals() method - checks if two reference type variables(classes, not structs) are referred to the same memory adress.
- The virtual Equals() method. (System.Object) - checks if two objects are equivalent.
- The static Equals() method - is used to handle problems when there is a null value in the check.
- The Equals method from IEquatable interface.
- The comparison operator == - usually means the same as ReferenceEquals, it checks if two variables point to the same memory adress. The gotcha is that this operator can be overrided to perform other types of checks. In strings, for instance, it checks if two different instances are equivalent.
Source¶
What is multicast delegate in C#?¶
Delegate can invoke only one method reference has been encapsulated into the delegate. It is possible for certain delegate to hold and invoke multiple methods. Such delegate called multicast delegate. Multicast delegate also know as combinable delegate, must satisfy the following conditions:
- The return type of the delegate must be void. None of the parameters of the delegate type can be delegate type can be declared as output parameters using out keywords.
- Multicast delegate instance is created by combining two delegates, the invocation list is formed by concatenating the invocation list of two operand of the addition operation. Delegates are invoked in the order they are added.
Actually all delegates in C# are MulticastDelegates, even if they only have a single method as target. (Even anonymous functions and lambdas are MulticastDelegates even though they by definition have only single target.)
Consider:
ublic partial class MainPage : PhoneApplicationPage
{
public delegate void MyDelegate(int a, int b);
// Constructor
public MainPage()
{
InitializeComponent();
// Multicast delegate
MyDelegate myDel = new MyDelegate(AddNumbers);
myDel += new MyDelegate(MultiplyNumbers);
myDel(10, 20);
}
public void AddNumbers(int x, int y)
{
int sum = x + y;
MessageBox.Show(sum.ToString());
}
public void MultiplyNumbers(int x, int y)
{
int mul = x * y;
MessageBox.Show(mul.ToString());
}
}
Source¶
What is jagged array in C#.Net and when to prefer jagged arrays over multi-dimensional arrays?¶
A jagged array (double[][]
) is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. If you care about speed then you always prefer jagged arrays over multi-dimensional arrays. The .NET runtime support (jitter and CLR) makes a strong distinction between vectors and arrays. A jagged array is a vector of vectors, you get all of the runtime optimizations when you use them. Multi-dimensional arrays don't. The speed difference is about a factor of two.
Only ever consider using multi-dimensional arrays if you favor the syntax convenience and have verified that array indexing is not on your program's critical path.
Source¶
Can you create sealed abstract class in C#?¶
No! It can not be created as abstract classes cannot be declared sealed.
Source¶
What is deep or shallow copy concept in C#?¶
- Shallow Copy is about copying an object's value type fields into the target object and the object's reference types are copied as references into the target object but not the referenced object itself. It copies the types bit by bit. The result is that both instances are cloned and the original will refer to the same object.
- Deep Copy is used to make a complete deep copy of the internal reference types, for this we need to configure the object returned by
MemberwiseClone()
.
In other words a deep copy occurs when an object is copied along with the objects to which it refers.
Source¶
What is a preprocessor directives in C#?¶
The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).
Source¶
Could you explain the difference between destructor, dispose and finalize method?¶
In C# terms, a destructor and finalizer are basically interchangeable concepts, and should be used to release unmanaged resources when a type is collected, for example external handles. It is very rare that you need to write a finalizer.
The problem with that is that GC is non-deterministic, so the Dispose()
method (via IDisposable
) makes it possible to support deterministic cleanup. This is unrelated to garbage collection, and allows the caller to release any resources sooner. It is also suitable for use with managed resources (in addition to unmanaged), for example if you have a type that encapsulates (say) a database connection, you might want disposing of the type to release the connection too.
Source¶
What's the difference between the System.Array.CopyTo() and System.Array.Clone()?¶
- Clone - Method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
- CopyTo - The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.
Source¶
What are the benefits of a Deferred Execution in LINQ?¶
In LINQ, queries have two different behaviors of execution: immediate and deferred. Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.
Consider:
With deferred execution, the above iterates your collection one time, and each time an item is requested during the iteration, performs the map operation, filters, then uses the results to build the list.
If you were to make LINQ fully execute each time, each operation (Select / Where) would have to iterate through the entire sequence. This would make chained operations very inefficient.
Source¶
What is the method MemberwiseClone() doing?¶
The MemberwiseClone() method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object.
- If a field is a value type, a bit-by-bit copy of the field is performed.
- If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
Consider:
public class Person
{
public int Age;
public string Name;
public IdInfo IdInfo;
public Person ShallowCopy()
{
return (Person) this.MemberwiseClone();
}
public Person DeepCopy()
{
Person other = (Person) this.MemberwiseClone();
other.IdInfo = new IdInfo(IdInfo.IdNumber);
other.Name = String.Copy(Name);
return other;
}
}
Source¶
What are circular references?¶
Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.
Source¶
What is the difference between lambdas and delegates?¶
They are actually two very different things.
- Delegate is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.
- Lambdas are very much like other methods, except for a couple subtle differences:
- A normal method is defined in a "statement" and tied to a permanent name, whereas a lambda is defined "on the fly" in an "expression" and has no permanent name.
- Lambdas can be used with .NET expression trees, whereas methods cannot.
Source¶
What are the differences between IEnumerable and IQueryable?¶
- The
IEnumerable<>
interface indicates that something can be enumerated across--in other words, you can do a foreach loop on it. - The
IQueryable<>
interface indicates that something has some kind of backing query provider that's capable of looking at Expressions that are given to it, and translate them into some kind of query.
What IQueryable
Source¶
Could you explain the difference between Func vs. Action vs. Predicate?¶
- Predicate: essentially
Func<T, bool>
; asks the question "does the specified argument satisfy the condition represented by the delegate?" Used in things likeList.FindAll
. - Action: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically.
- Func: Used extensively in LINQ, usually to transform the argument, e.g. by projecting a complex structure to one property.
Source¶
Explain what is weak reference in C#?¶
The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.
Source¶
Explain the difference between IQueryable, ICollection, IList & IDictionary interfaces?¶
All of these interfaces inherit from IEnumerable. That interface basically lets you use the class in a foreach
statement (in C#).
- ICollection is the most basic of the interfaces you listed. It's an enumerable interface that supports a Count and that's about it.
- IList is everything that ICollection is, but it also supports adding and removing items, retrieving items by index, etc. It's the most commonly-used interface for "lists of objects".
- IQueryable is an enumerable interface that supports LINQ. You can always create an IQueryable from an IList and use LINQ to Objects, but you also find IQueryable used for deferred execution of SQL statements in LINQ to SQL and LINQ to Entities.
- IDictionary is a different animal in the sense that it is a mapping of unique keys to values. It is also enumerable in that you can enumerate the key/value pairs, but otherwise it serves a different purpose than the others you listed.
Source¶
in C#, when should we use abstract classes instead of interfaces with extension methods?¶
-
Abstract classes work by inheritance. Being just special base classes, they model some is-a-relationship.
-
Interfaces on the other hand are a different story. They don't use inheritance but provide polymorphism (which can be implemented with inheritance too). They don't model an is-a relationship, but more of a it does support.
Applying extension methods to an interface is useful for applying common behaviour across classes that may share only a common interface.
Source¶
Can you add extension methods to an existing static class?¶
No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper class. Also extension methods is just syntactic sugar.
Consider:
public static string SomeStringExtension(this string s)
{
//whatever..
}
// When you then call it
myString.SomeStringExtension();
// the compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
Source¶
Implement the "Where" method in C¶
Consider:
public static IEnumerable<T> Where<T>(this IEnumerable<T> items, Predicate< T> prodicate)
{
foreach(var item in items)
{
if (predicate(item))
{
// for lazy/deffer execution plus avoid temp collection defined
yield return item;
}
}
}
Source¶
What is the “volatile” keyword used for?¶
In C# volatile
tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself (such as the operating system, the hardware, or a concurrently executing thread.). The compiler will then avoid any optimisations that may result in problems if the variable changes "outside of its control".
Source¶
Calculate the circumference of the circle¶
The preferred answer would be of the form:
Since we don’t have access to the private radius
field of the object, we tell the object itself to calculate the circumference, by passing it the calculation function inline.
A lot of C# programmers shy away from (or don’t understand) function-valued parameters. While in this case the example is a little contrived, the purpose is to see if the applicant understands how to formulate a call to Calculate
which matches the method’s definition.
Alternatively, a valid (though less elegant) solution would be to retrieve the radius value itself from the object and then perform the calculation with the result:
Either way works. The main thing we’re looking for here is to see that the candidate is familiar with, and understands how to invoke, the Calculate
method.
Source¶
What is the use of static constructors?¶
A static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).
You can't overload it.