Page 1

C# Interview Questions and Answers

C# What are the differences between Abstract and interface? Ans: 1) Abstract cannot be instantiated but we can inherit. Interface it cannot be inherit it can be instantiate 2) Interface contain only declarations no definitions. Abstract contain declarations and definitions. 3) The class which contains only abstract methods is interface class. A class which contains abstract method is called abstract class 4) Public is default access specifier for interface we don’t have a chance to declare other specifiers. In abstract we have chance to declare with any access specifier What is a singleton?

A singleton is a design pattern used when only one instance of an object is created and shared; that is, it only allows one instance of itself to be created. Any attempt to create another instance simply returns a reference to the first one. Singleton classes are created by defining all class constructors as private. In addition, a private static member is created as the same type of the class, along with a public static member that returns an instance of the class. Here is a basic example: public class SingletonExample { private static SingletonExample _Instance; private SingletonExample () { } public static SingletonExample GetInstance() { if (_Instance == null) { _Instance = new SingletonExample (); } return _Instance; } } What is boxing? Boxing is the process of explicitly converting a value type into a corresponding reference type. Basically, this involves creating a new object on the heap and placing the value there. Reversing the process is just as easy with unboxing, which converts the value in an object reference on the heap into a corresponding value type on the stack. The unboxing process begins by verifying that the recipient value type is equivalent to the boxed type. If the operation is permitted, the value is copied to the stack. What are differences between Array list and Hash table? 1) Hash table store data as name, value pair. While in array only value is store. 2) To access value from hash table, you need to pass name. While in array, to access value, you need to pass index number. 3) you can store different type of data in hash table, say int, string etc. while in array you can store only similar type of data. What are differences between System.StringBuilder and System.String? The main difference is system.string is immutable and system.stringbuilder is a mutable. Append keyword is used in string builder but not in system.string. Immutable means once we created we cannot modified. Suppose if we want give new value to old value simply it will discarded the old value and it will create new instance in memory to hold the new value. How do you prevent a class from being inherited? The sealed keyword prohibits a class from being inherited.

Page 1 of 9

C# What is the execution entry point for a C# console application? The Main method. How do you initiate a string without escaping each backslash? You put an @ sign in front of the double-quoted string. String ex = @"This has a carriage return\r\n" What is the difference between a struct and a class? Structs cannot be inherited. Structs are passed by value and not by reference. Structs are stored on the stack not the heap. The result is better performance with Structs.

How many types of memories are there in .net? Ans: Two types of memories are there in .net stack memory and heap memory What is the difference between primary key and unique key with not null? Ans: There is no difference between primary key and unique key with not null. What is boxing and unboxing concepts in .net? Ans: Boxing is a process of converting value type into reference type Unboxing is a process of converting reference type to value type. What are the differences between value type and reference type? Ans: Value type contain variable and reference type are not containing value directly in its memory. Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration What do you mean by String objects are immutable? String objects are immutable as its state cannot be modified once created. Every time when we perform any operation like add, copy, replace, and case conversion or when we pass a string object as a parameter to a method a new object will be created. Example: String str = "ABC"; str.Replace("A","X"); Here Replace() method will not change data that "str" contains, instead a new string object is created to hold data "XBC" and the reference to this object is returned by Replace() method. So in order to point str to this object we need to write below line. str = str.Replace("A","X"); Now the new object is assigned to the variable str. earlier object that was assigned to str will take care by garbage collector as this one is no longer in used. What is dll hell problem in .NET and how it will solve? Ans: Dll hell is kind of conflict that occurred previously, due to the lack of version supportability of dll for (within) an application .NET Framework provides operating system with a global assembly cache. This cache is a repository for all the .net components that are shared globally on a particular machine. When a .net component installed onto the machine, the global assembly cache looks at its version, its public key and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between the different versions of same component, or DLL

Page 2 of 9

C# What is a Partial class? Instead of defining an entire class, you can split the definition into multiple classes by using partial class keyword. When the application compiled, c# compiler will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of classes without needing to share same physical file Ex: Public partial class employee { Public void somefunction() { } } Public partial class employee { Public void function () { } } What is difference between constants, read-only and, static? Constants: The value can’t be changed Read-only: The value will be initialized only once from the constructor of the class. Static: Value can be initialized once. How to get the version of the assembly? Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString(); What is the GAC? The GAC is the Global Assembly Cache. Shared assemblies reside in the GAC; this allows applications to share assemblies instead of having the assembly distributed with each application. What is the location of Global Assembly Cache on the system? Ans: c:\Windows\assembly What is the serialization? Ans: Serialization is a process of converting object into a stream of bites. What is synchronization? Ans: The mechanism needed to block one thread access to the data. If the data is being accessed by another thread. Synchronization can be accessed by using system.monitor class A monitor class methods are enter, exit, pulse for this lock statement is also used Suppose if we need to synchronize some data at that time we need to place that data in this block Lock { } Whatever the data has been placed into the lock block that data has been blocked What are the thread priority levels? Ans: Thread priority levels are five types 0 - Zero level 1 - Below Normal 2 - Normal 3 - Above Normal 4 - Highest By Default priority level is 2

Page 3 of 9

C# What is the difference between .tostring(), Convert.tostring()? Ans: The basic difference between them is “Convert” function handles NULLS while “.ToString()” does not it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe. What is static keyword in .Net? Ans: Static is same as constant variable but we can change the value of static variable and we can access the variables without creating any instances What do you mean by Early and Late Binding? Early binding - Assigning values to variables during design time or exposing object model at design time. Late Binding - Late binding has the same effect as early binding. The difference is that you bind the object library in code at run-time How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class. What is the difference between ref & out parameters? An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter. What is serialization? Serialization is the process of converting an object into a stream of bytes. De-serialization is the opposite process of creating an object from a stream of bytes. Serialization / De-serialization is mostly used to transport objects. What are the difference between Structure and Class? Structures are value type and Classes are reference type Structures cannot have contractors or destructors. Classes can have both contractors and destructors. Structures do not support Inheritance, while Classes support Inheritance. What is Delegates? Delegates are a type-safe, object-oriented implementation of function pointers and are used in many situations where a component needs to call back to the component that is using it. What are value types and reference types? Value types are stored in the Stack. Examples : bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut, uint, ulong, ushort. Reference types are stored in the Heap. Examples : class, delegate, interface, object, string. What is the difference between break and continue statement? The break statement is used to terminate the current enclosing loop or conditional statements in which it appears. We have already used the break statement to come out of switch statements. The continue statement is used to alter the sequence of execution. Instead of coming out of the loop like the break statement did, the continue statement stops the current iteration and simply returns control back to the top of the loop.

Page 4 of 9

C# What is the difference between Array and Arraylist? An array is a collection of the same type. The size of the array is fixed in its declaration. A linked list is similar to an array but it doesn’t have a limited size. Is String is Value Type or Reference Type in C#? String is an object(Reference Type). Why is the virtual keyword used in code? The Virtual keyword is used in code to define methods and the properties that can be overridden in derived classes. Which namespace enables multithreaded programming in XML? System.Threading What is Static Method? It is possible to declare a method as Static provided that they don't attempt to access any instance data or other instance methods. What is lock statement in C#? Lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released. What is Reflection? Enables us to get some information about objects in runtime Difference Between dispose and finalize method? Dispose is a method for realse from the memory for an object. For eg: <object>.Dispose. Finalize is used to fire when the object is going to realize the memory.We can set a alert message to says that this object is going to dispose. Which namespace is required to use Generic List? System.Collections.Generic What’s a delegate? A delegate object encapsulates a reference to a method. When do you absolutely have to declare a class as abstract? 1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract. How to create a strong name? To create a strong name key use following code C:\>sn -k s.snk Strong name key is used to specify the strong name used to deploy any application in the GAC (Global Assembly Catch) in the system. What is operator overloading in C#? Operator overloading is a concept that enables us to redefine (do a special job) the existing operators so that they can be used on user defined types like classes and structs. Difference between Static and ReadOnly? Static: A variable that retains the same data throughout the execution of a program. ReadOnly: you can’t change its value.

Page 5 of 9

C# Difference Between String and StringBuilder? String Class Once the string object is created, its length and content cannot be modified. Slower StringBuilder Even after object is created, it can be able to modify length and content. Faster Give Some Examples of Generic Classes? List<T>,Queue<T>,Stack<T>,LinkedList<T>,HashSet<T> Explain Queue and Stack A Queue is a collection where elements are processed in First in First Out(FIFO) Stack is collection where elements are processed in Last In First Out What is the difference between Parse and TryParse method? Parse method is used to parse any value to specified data type. TryParse is a good method if the string you are converting to an interger is not always numeric.The TryParse method returns a boolean to denote whether the conversion has been successfull or not How can you make your machine shutdown from your program? Process.Start("shutdown", "-s -f -t 0"); What is the use of ?? operator in C#? This operator allows you to assign a value to a nullable type if the retrieved value is in fact null. Why 'static' keyword is used before Main()? Program execution starts from Main(). S it should be called before the creation of any object. By using static the Main() can now be called directly through the class name and there is no need to create the object to call it. So Main() is declared as static. Can we declare a class as Protected? No, a class can not be declared as Protected. What is the difference between IQueryable<T> and IEnumerable<T> interface? IEnumerable<T> IEnumerable<T> is best suitable for working with in-memory collection. IEnumerable<T> doesn't move between items, it is forward only collection. IQueryable<T> IQueryable<T> best suits for remote data source, like a database or web service. IQueryable<T> is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries). So when you have to simply iterate through the in-memory collection, use IEnumerable<T>, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable<T>. Define different Access modifiers in C# The access modifier is the key of Object Oriented Programming, to promote encapsulation, a type in C# should limit its accessibility and this accessibility limit are specified using Access modifiers. They are - Public, Internal, Protected, Private, Protected Internal Public: When used that type (method or variable) can be used by any code throughout the project without any limitation. This is the widest access given to any type and we should use it very judiciously. By default, enumerations and interface has this accessibility. Internal: When used that type can be used only within the assembly or a friend assembly (provided accessibility is specified using InternalVisibleTo attribute). Here assembly means a .dll.

Page 6 of 9

C# For example if you have a .dll for a Data Access Layer project and you have declared a method as internal, you will not be able to use that method in the business access layer) Similarly, if you have a website (not web application) and you have declared internal method in a class file under App_Code then you will not be able to use that method to another class as all classes in website is compiled as a separate .dll when first time it is called). Internal is more limited than Public. Protected When used that type will be visible only within that type or sub type. For example, if you have a aspx page and you want to declare a variable in the code behind and use it in aspx paeg, you will need to declare that variable as at least protected (private will not work) as code behind file is inherited (subclass) by the aspx page. Protected is more secure than Internal. Private When used that type will be visible only within containing type. Default access modifier for methods, variables. For example, if you have declared a variable inside a method, that will be a private variable and may not be accessible outside that method. Private is the most secure modifiers than any other access modifiers as it is not accessible outside. Protected Internal This is not a different type of access modifiers but union of protected and internal. When used this type will be accessible within class or subclass and within the assembly. What is the use of virtual, sealed, override, and abstract? • The • The • The • The make

use of virtual keyword is to enable or to allow a class to be overridden in the derived class. use of sealed keyword is to prevent the class from overridden i.e. you can’t inherit sealed classes. use of override keyword is to override the virtual method in the derived class. use of abstract keyword is to modify the class, method, and property declaration. You cannot directly calls to an abstract method and you cannot instantiate an abstract class.

Does the finally block execute even when we have unhandled exceptions? Yes, the finally block executes even if the exception is unhandled What is Value Types versus Reference Types? The Value Types which includes most built-in types such as numeric types, char types and bool types as well as the custom struct and enum types. The content of a Value Type variable is simply a value. But in case of Reference Types, it includes all classes, array, interface, and delegate types. This is quite different from value type. It contains two parts that is an object and the reference to that object. The content of this type is a reference to an object that contains a value. The basic difference between them is, how they are handled inside the memory. How can we sort elements in an array in descending order ? We have 2 different methods like Array.Sort()---> Which sorts the given array Array.Reverse()---> Which reverses the array What are the different Name Spaces that are used to create a localized application? There are 2 different name spaces required to create a localized application they are

. System.globalization . System.Resource MultiThreading: A multithreaded application allows you to run several threads, each thread runs in its own process. So that you can run step1 in one thread and step 2 in another thread at the same time. Can multiple catch blocks be executed? No What method is used to stop a running thread? Thread.Abort

Page 7 of 9

C# What is the difference between DirectCast and CType ? DirectCast requires the object variable to be the same in both the run-time type and the specified type. If the specified type and the run-time type of the expression are the same, then the run-time performance of DirectCast is better than that of CType. Ctype works fine if there is a valid conversion defined between the expression and the type. What is IDisposable interface in .NET? IDisposable interface is used to release the unmanaged resources in a program. Explain Boxing and unboxing in c#? Boxing and unboxing in c# Boxing is the process of converting a value type to the reference type. Unboxing is the process of converting a reference type to value type. How to copy one array into another array ? We can copy one array into another array by using copy To() method. How to get the total number of elements in an array ? By using Length property, we can find the total number of elements in an array. What is serialization? While sending an object from a source to destination, an object will be converted into a binary/xml format. This process is called serialization . Thread.Sleep(int) method the integer parameter that represents Time that particular Thread should wait. What that Time Unit represents ? Time in MilliSeconds What is the difference between ArrayList and Generic List in C#? Generic collections are TypeSafe at compile time. So No type casting is required. But ArrayList contains any type of objects in it What is the difference between IEnumerable and IList? IEnumerable<T> represents a series of items that you can iterate over IList<T> is a collection that you can add to or remove from. What is difference between is and as operators in c#? “is” operator is used to check the compatibility of an object with a given type and it returns the result as Boolean. “as” operator is used for casting of object to a type or a class.

C# Q n A  

Interview Questions and Answers

Read more
Read more
Similar to
Popular now
Just for you