C# is a modern, high level, general purpose object oriented programming language. This language is principal language of .Net framework. The design goal of the language was software robustness, durability & programmer productivity. It can be used to create a console application, GUI application, web application both on PC or embedded systems.
A class describes all attributes of objects as well as the method that implements the behavior of member object. Basically, it represents a blue print of object.
It is a template of an object. A class contains data & behavior of an entity.
Example: Aircraft.
Data: Model number of aircraft, Color of aircraft, category of aircraft etc.
Behavior/Method: Duration of flight, number of passengers etc.
An object is an instance of the class. It is a basic unit of the system. An object is an entity that has attributes, behavior & identity. Attributes & behavior of an object is defined by the class definition.
They both look very much same but they are not same. The class is definition while the object is the instance of the class created. The class is blue print while objects are actual
objects existing in the world.
Example: Car has attributes & method like speed, brake, type of car etc.
Following are the advantages of C#
Following are the IDE’s used for C# development
Struct & Class both are the user defined data type but have some major differences:
# | Struct | Class |
---|---|---|
1. | Structure are value type in C# & it inherits from System.ValueType. | Classes are reference type & it inherits from the System.Object Type. |
2. | Structure use stack to store value. | classes use heap to store value. |
3. | Structure can not be declared as protected . | Classes can not declare as protected. |
4. | We can not be able to use inheritance in Structure. | We can use inheritance in classes. |
5. | The struct can have the only constructor. | The class can have the constructor and destructor. |
6. | Structure objects can not destroy using GC. | Objects created from classes are terminated using GC. |
7. | The struct can instantiate without using the new keyword.. | The new keyword should be used to create the object for the class. |
8. | The struct can only inherit the interfaces. | The class can inherit the interfaces, abstract classes. |
Oops stands for object oriented programming system.
It is a problem-solving technique to think real world problems in terms of objects.
Following are different properties provided by oops
# | Abstraction | Encapsulation |
---|---|---|
1. | Abstraction solves the problem at design level. | Encapsulation solves the problem at the implementation level. |
2. | Abstraction is set to focus on the object instead of how it does it. | Encapsulation means hiding the internal details or mechanics of how an object does something. |
3. | Abstraction is used for hiding the unwanted data and giving only relevant data. | Encapsulation is hiding the code and data into a single unit to protect the data from the outer world. |
4. | Abstraction is implemented using interface & abstract class. | Encapsulation is implemented using private & protected access modifiers. |
5. | Abstraction is outer layout in terms of design. | Encapsulation is inner layout in terms of implementation. |
e.g. | Outer Look of an iPhone, like it has a display screen. | Inner Implementation detail of an iPhone, how Display Screen are connected with each other using circuits. |
The sealed class is used to stop the class from being inherited from other classes. If you define a class in C# as "Sealed" & "nonheritable" in VB.NET, then you can not inherit the class further.
Value types directly contain data and derived from System.ValueType.
Value types use the stack to store value.
Example: int, float, char, Bool, short
reference types stored the address of memory where data is stored
reference types use the heap to store value.
Example: Class, Interface, String, Object, Delegate, Array
# | Struct | Class |
---|---|---|
1. | They are stored on stack. | They are stored on heap. |
2. | Memory is allocated at compile time. | Memory is allocated at runtime. |
3. | The value type is popped on its own from the stack when they go out of scope. | Required garbage collector to free memory. |
4. | Value type contains actual value. | Reference type contains reference to a value. |
5. | Cannot contain null values. However, this can be achieved by nullable types. | Can contain null values. |
e.g. | int, float, char, Bool, short. | Class, Interface, String, Object, Delegate, Array. |
using SizeOf operator.
Example: Console.WriteLine("The size of long is {0}.", sizeof(long));
output: The size of long is 8.
Following are different types of parameter in c#
1. Value parameter(in)
2. Reference parameter (ref)
3. Output parameter(out)
4. Parameter Array(param)
"out" parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before it is used.
Array
1. Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime.
2. Arrays belong to System.Array namespace.
ArrayList
1. Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type.
2. Arraylist belongs to System.Collection namespaces
"Const" keyword is used for making an entity constant.
Example: const string _name = "techstudy";
Once we define a variable as a const then we can’t reassign the value of that variable(string _name).
Access Modifiers are basically used to control the accessibility of types and members with in the types. In C# there are 5 different types of Access Modifiers.
1. Public: Public is the most common access specifier in C#. It can be accessed from anywhere, that means there is no restriction on accessibility. It is accessible to all classes & projects.
2. Private: The range of the accessibility is limited only within the classes or struct in which they are declared.
3. Protected: All members in the current class & in derived classes can access the variables.
4. Internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.
5. Protected Internal: The protected internal access specifier allows a class to hide its member functions & member variables from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
In C# there is a "try...catch & finally" block to handle the error.
try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } finally { // statements to be executed }
No. Once any exception has occurred it executes specific exception catch block and the control comes out.
using keyword is used to include a namespace in the program. A program generally has multiple using statements.
Using Array.sort(array) function.
No! C# does not support multiple inheritance.
1) While loop checks for the condition first so it may not even enter into the loop if the condition is false.
2) do while loop executes the content of the loop once before checking the condition of the while.
3) For loop is similar to while loop except, the initialization of variable, condition check & increment happens at one place.
"Const" keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is always mandatory to constant variables.
"readonly" variable value can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.
Dispose: This method uses interface – "IDisposable" interface & it will free up both managed and unmanaged codes like - database connection, files etc. It belongs to the IDisposable interface. Implement this method when you are writing a custom class that will be used by other users.
Finalize: This method is called internally unlike Dispose method which is called explicitly. It is called by the garbage collector and can’t be called from the code. Finalize belongs to System.Object class. Implement this method when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.
The string is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create a new instance in memory to hold the new value.
String belongs to System namespace
=>Example
string str = "hi";
//It creates a new string instance instead of changing the old one
str += "help";
str += "test";
StringBuilder
String builder is mutable. Mutable means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.
StringBuilder belongs to System.Text namespace
=> Example
StringBuilder sb = new StringBuilder("");
//It does not creats new instance for every time.
sb.Append("hi");
sb.Append("help ");
string str = sb.ToString();
1. ArgumentNullException
2. NullReferenceException
3. IndexOutOfRangeException
4. DivideByZeroException
5. StackOverflowException
6. InvalidOperationException etc.
Delegates are type safe pointers, unlike function pointers as in C++. A delegate is used to represent the reference to the methods of some return type and parameters.
Delegates are required because they can be used to write much more generic type safe functions.
Following are the types of delegates in C# -
1. Single Delegate
2. Multicast Delegate
3. Generic Delegate
A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is assigned to a method.
Variable types do not hold null values so to hold the null values we have to use nullable types.
nullable types can have values either null or other values as well.
Eg: int? nullvariable = null;
Boxing: This is the process of converting from value type to reference type.
Example
int i = 67; // i is a value type
object o = i; // i is boxed
System.Console.WriteLine(i.ToString()); // i is boxed
UnBoxing: It’s the process of converting reference type to value type.
System.Collections.ArrayList list = new System.Collections.ArrayList(); // list is a reference type
int n = 67; // n is a value type
list.Add(n); // n is boxed
n = (int)list[0]; // list[0] is unboxed
We can't use "this" in a static method because we can only use static variables/methods in a static method.
Interface class is an abstract class which has only public abstract methods & the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.
We create an abstract class when we define a template that needs to be followed by all the derived classes. Abstract class can have implementation which should be implemented in the child class.
# | Abstract class | Interface Class |
---|---|---|
1. | Abstract class can have implementation for some of its members or methods. | Interface class can not have implementation for any its members. |
2. | Abstract class can have fields. | Interface class can not have fields. |
3. | Abstract class can inherit from another Abstract class or another interface. | Interface class can inherit from another interface class only. Interface cannot inherit from an abstract class. |
4. | Abstract class members can have access modifiers. | Interface class members can not have access modifiers. |
5. | Abstract class doesn't support multiple inheritance. | Interface supports multiple inheritance. |
e.g. |
Example: public abstract class Shape{ public abstract void draw(); } |
Example: public interface Drawable{ void draw(); }. |
# | Static polymorphism | Dynamic polymorphism |
---|---|---|
1. | Method overloading would be an example of static polymorphism. It uses the concept of early binding(Compile time binding). | Method Overriding would be an example of dynamic polymorphism. It uses the concept of late binding(Runtime Binding). |
2. | Static polymorphism is faster than dynamic polymorphism because of early binding. | Dynamic polymorphism is faster than static polymorphism because of late binding. |
3. | Static polymorphism is less flexible as all things execute at compile time. | Dynamic polymorphism is more flexible as all things execute at run time. |
4. | It is achieved by function overloading and operator overloading. | It is achieved by abstract classes and virtual functions. |
Methods can be overloaded using the different order of parameters, data types for the parameter, and using a different number of parameters.
The virtual keyword is used while defining a class to specify that the method and properties of that class can be overridden in derived class.
Generics are used to make reusable code classes to decrease the code redundancy, increase type safety and performance. Using generics, we can create a collection of classes. To create a generic collection, System.Collections.Generic namespace should be used.
Colon is used as inheritance operator in C#. Just place a colon and then the class name.
Example: public class DerivedClass : BaseClass
"is" operator is used to checking the compatibility of an object with a given type and it returns the result as Boolean.
"as" operator is used for casting of an object to a type or a class.
Yes! C# is managed code because it uses Common language runtime(CLR) to compile C# code.
Public: The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone.
Static: The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.
Void: The keyword void is a type modifier that states that the Main method does not return any value.
“CopyTo()” method can be used to copy the elements of one array to other.
“Clone()” method is used to create a new array to contain all the elements which are in the original array.
Partial classes concept added in .Net Framework 2.0 & it allows us to split the business logic into multiple files with the same class name along with “partial” keyword.
1. ArrayList
2. Stack
3. Queue
4. SortedList
5. HashTable
6. Bit Array
It is a feature of modern OS with which we can run multiple programs at the same time.
Example: Word, Excel etc.
It is a subset of multitasking. Instead of switching between programs this feature switches between different part of the same program.
Example: Writing in MS-Word and It also checking spelling using spell-checker in the background
It is a basic unit to which OS allocates processor time.
Example: .Net Framework program has at least 2 threads running one
is the main program & Second is Garbage collector(GC).
Syntax to change thread priority
Threading.Priority = Threadpriority.priorityUnit;
Levels of priority
1) Threadpriority.Highest (10)
2) Threadpriority.Abovenormal (7)
3) Threadpriority.Normal(5)
4) Threadpriority.Belownormal(3)
5) Threadpriority.Lowest(1)
"Thread.Currentthread" refers to the current thread running the method.
It is public static property.
Thread execution can be paused by calling the Thread.Sleep method. This method takes on integer value that determines how long the thread should sleep
Example: Thread.currenttime.sleep(2000) // 2 Seconds
Thread.sleep(System.Threading.Timeout.Infinite)
To interrupt this sleep method you can call-
Thread.interrupt method
It is similar to sleep & interrupts. Suspend allow you to block thread until another thread calls thread.resume.
The difference between sleep & suspend is that suspend does not immediately place a thread in a wait state. the thread does not suspend until the .Net runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.
Thread.Abort stops the thread execution at the moment itself.
There are two versions of Thread.join
1) Thread.join()
2) Thread.join(integer) this returns a bool value.
Example: If we have two threads-> Thread1 & thread2 while executing "Thread1" you call "Thread2.Join()". So "Thread1" will wait until "Thread2" has completed its execution and again invoke "Thread1".
Thread.join(integer) ensures that thread does not wait for a long time. once it exceeds the provided specific time, It will start the waiting thread.
If you want to transfer an object through network then you have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called serialization.
Object pool is a container of ready to use objects. It reduce the overhead of creating new objects.
Circular reference is state in which 2 or more resources are interdependent on each other causes the lock condition and make the resources unusable.
A Hashtable is a collection of key-value pairs. It contains values based on the key.
In Constructor overloading, n number of constructors can be created for the same class. But the signatures of each constructor should always vary
1 2 3 4 5 6 7 |
public class Student { public Student() { } public Student(String fullname) { } } |
Indexers are known as the smart arrays in C#. It allows the instances of a class to be indexed in the same way as array.
1 |
public int this[int index] |
In singleton pattern, a class can only have one instance and provides access point to it globally.
1 2 3 4 |
Public sealed class Singleton { Private static readonly Singleton _instance = new Singleton(); } |
Name of C# Compiler is – CSC.
“Concat” method of String class is used to concatenate two strings
1 |
string.Concat(firstnamestr, lastnamestr)
|
Using break statement, you can 'jump out of a loop' while by using continue statement, you can 'jump over one iteration' and then resume your loop execution.
So Guys, this brings us to the end of this article on C# Interview Questions and answers. I hope this post world helped in adding up to your knowledge. Wishing you all the best for your interview.
09 August 2019 3550 Written By: Rohit
In case you are looking for the most common Technical Interview Questions, read along:
© 2020 Tech Study. All rights reserved | Developed by Tech Study| Privacy Policy | Sitemap