Sei sulla pagina 1di 12

What’s C# ?

C# (pronounced C-sharp) is a one kind of objects oriented language developed by Microsoft Corporation.
It is designed with the combination of C and C++. It has taken a lot of concepts from Java.

C# Data Types
In a programming language Data Types describes what type of data a variable can hold. C# is a
strongly typed language. That means every variable and object must have a declared type. When
we declare a variable, we have to tell the compiler about what type of the data the variable can hold.
In C# programming language, Data types are divided into three categories:
1. Value Type
2. Reference Type
3. Pointer Type

What is Boxing and Unboxing?


In C# it is possible to convert a value of one type to a value of another type. The operation or
process of Converting a Value Type to a Reference Type is called Boxing and the operation or
process of converting a Reference Type to a Value Type is called Unboxing.

Value Type
A Value Type variable stores a copy of the value in the memory. Some common examples are int,
char, float. When we declare an int type, the system allocates memory to store the value.

Reference Type
A Reference Type stores the address of the value in the memory. It does not contain the actual data
stored in a variable. They contain a reference to the variables. Some built-in reference types are:
object, dynamic and string. The user-defined reference types are: class, interface, delegate, Array.

Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have the same
capabilities as in C or C++.

Object
Object is a built-in reference data type. It is a base class for all predefined and user-defined data
types. A Class is a logical structure that represents a real world entity. This means that the
predefined and user-defined data types are created based on the object class.

String
String is a built-in reference data type. A string type signifies Unicode character string values. It
allows you to assign and manipulate string values. Once strings are created, they cannot be
modified.
Class
A Class is user-defined structure that contains variables and methods.
Delegate
A Delegate is a user-defined reference type that stores the reference of one or more methods.
Interface
An interface is a type of user-defined class that is used for multiple inheritance.
Array
An array is a user-defined data structure that contains values of the same data type, such as marks
of Student.
What is Enumerations or enums?
Enumerations or enums is a set of named integer constants. Enumerated type is declared using the
enum keyword. In C# enums are value types and enum constants must be integral numeric values.
Its index starts from 0;
Example
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Output
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine(“Monday: {0}”, WeekdayStart);
Console.WriteLine(“Friday: {0}”, WeekdayEnd);
Monday: 1
Friday: 5

What are the types of comment in C# with examples?


Single line
//This is a Single line comment.
Multiple line (/* */)
/*This is a multiple line comment
We are in line 2
Last line of comment*/
XML Comments (///)
/// <summary>
/// Set error message for multilingual language.
/// </summary>
What is an object?
An object is an instance of a class through which we access the methods of that class. “New”
keyword is used to create an object. A class that creates an object in memory will contain the
information about the methods, variables and behavior of that class.
What is Abstraction?
Abstraction is a process of showing only the relevant and essential information to the users without
showing unnecessary information.
What is Encapsulation?
Encapsulation is a process of protecting unwanted access of information. It is an attribute of an
object.Abstraction and encapsulation are related features in OOP or Object Oriented Programming.
Abstraction allows making relevant information visible and encapsulation protect unwanted access of
information.Encapsulation is implemented by using access modifiers. An access modifier defines the
scope and visibility of a class member. C# supports the following access modifiers:
1. Public
2. Private
3. Protected
4. Internal
5. Protected internal
What is Polymorphism?
The word polymorphism comes from Greek and it means having multiple forms. This is one of the
essential concepts of object oriented programming. Inheritance is related to class but polymorphism
is related to object methods. A common example of polymorphism in C# : Function overloading,
Operator overloading
What is Inheritance?
Inheritance is a process of reusability of code. It eliminates the use of redundant code. In this system
child class can obtained all the features of parent class. Parent class is called based class and the
child class is called derived class.
Differentiate strong typing and weak typing
In strong typing the data types of variable are checked at compile time. In weak typing the data types
of variable are checked at runtime. In strong typing there is no chance of compilation error. Scripts
use weak typing and that’s why issues arise at runtime.
C# language is?
C# language is strong typing. All .Net languages are strongly-typed.
What is the difference between Array and Array List?
Both Array and Array List is a container to store similar type of data. But it has a basic difference.
The size of the array is fixed. But the size of Array List is not fixed.
What is Queue?
Queue is container of object where data are inserted and retrieved according to First In First Out
(FIFO) structure. Its initial capacity is 32 elements.
What is Stack?
Stack is container of object where data are inserted and retrieved according to Last In First Out
(LIFO) structure. Its initial capacity is 32 elements.
What are the differences between System.String and System.Text.StringBuilder classes?
System.String is immutable. It means that we can’t modify a string at all. The result of modification is
a new string.
When we modify the value of a sting variable then a new memory is allocated for the new value and
the previous memory is released.
System.StringBuilder is mutable. It means that a string can be modified without allocation new
memory. That’s why System.StringBuilder is more effective.

What is HashTable?
A hashtable or a hash map is a data structure that is used to implement an associative array. It
associates keys with values. The primary operation in hash table is look like: given a key (e.g. a
student’s name), find the corresponding value (e.g. that student’s ID number). It uses a hash
function to compute an index into an array of buckets or slots, from which the correct value can be
found. It is an older .NET Framework. It is slower than the generic Dictionary type.
Example:
Hashtable hashtable = new Hashtable();

hashtable.Add(100, "Dhaka");

hashtable.Add(200, "London");

// Display the keys.

foreach (int key in hashtable.Keys)

Console.WriteLine(key);

// Display the values.


foreach (string value in hashtable.Values)

Console.WriteLine(value);

Output
//First loop
100
200
//Second loop
Dhaka
London
When to use a HashTable?
When we need to search items quickly by key.
We can use IList or IEnumerable etc for a matching key but that will take O(n) time rather than O(1)
for Hashtable or Dictionary.
Differences between Hashtable and Dictionary. Hashtable vs. Dictionary
Hashtable:
1. It returns null if we try to find a key which does not exist
2. It is slower than dictionary because it requires boxing and unboxing
3. All the members in a Hashtable are thread safe
4. It is not a generic type that means we can’t use it with any data type
Dictionary:
1. It returns error if we try to find a key which does not exist
2. It is faster than a Hashtable because there is no boxing and unboxing
3. Only public static members are thread safe
4. It is a generic type that means we can use it with any data type
What is Delegates?
A delegate in C# allows you to pass method of one class to objects of other class that can call these
methods.
OR
A delegate is an object that holds the reference to a method.
In C++ it is called function pointer.
How do you inherit a class into other class in C#?
Colon(:) is used as inheritance operator in C#. To inherit a class just places a colon and then the
class name.
public class DerivedClass : BaseClass
What is the difference between method overriding and method overloading?
Overloading
1. It is a compile time polymorphism
2. At the compile time the compiler know which object is assigned for which class
3. Method name will be same, parameters will be different and its return type may or may not same
4. Example- operator overloading, function overloading
Overriding
1. It is a run time polymorphism
2. At the compile time the compiler didn’t know which object is assigned for which class. Compiler knows
it at run time
3. Method name will be same, parameters will be same and its return type will be same
4. Example- virtual function
What are Constructor & Destructor?
Constructor is a member function and its name is as like as class name. It is used to initialize the
class object. Constructor & Destructor both are necessary for every class. If we don’t create them
compiler automatically create them by himself. Constructor & Destructor has no return type. It is
called when a class object is created. Constructor & Destructor has no statement primarily. But we
can create custom statement. Constructor may have parameter or not.
Destructor is used to delete object instance from the memory. We need to destroy object instance
after its task. If we don’t does this compiler automatically do this? Its name is as like class name.
Only extra ~ sign is used before its name. It has no parameter and it doesn’t accept any operator.

What is the difference between static or dynamic assemblies?


Assemblies can be static or dynamic.
Static Assemblies are stored on the disk permanently. They can include .NET Framework classes,
interfaces as well as resource files (bitmaps, JPEG files). They are not loaded directly from the
memory. They are loaded form the disk when CLR requests for them. When we compile the C#
codes Static Assemblies are generated. They are stored on disk in portable executable (PE) files.
Dynamic Assemblies are not stored on the disk before execution. They are not saved to disk before
execution. We can save them to disk after they have executed. They are loaded form the memory
directly. They are created dynamically at run time when application request for them.

What are the difference between Structure and Class?


Structures are value type and Classes are reference type.
Structures cannot have constructor or destructors.
Classes can have both constructor and destructors.
Structures do not support Inheritance, but Classes support Inheritance.
What is Authentication and Authorization?
Authentication is the process of identifying user. Authentication is identifying/validating the user
against the credentials (username and password).
Authorization is the process of granting access to those users based on identity. Authorization allows
the access of specific resource for a user. Authorization performs after authentication
What are the types of Authentication?
There are 3 types of Authentication. Windows, Forms and Passport Authentication.
What is Exceptions?
An exception is a problem that arises during the execution time of a program. A common example of
exceptions is: when we try to divide a number by zero.
How exceptions are handled in C#?
C# provides 3 built-in objects try, catch and finally to handle exception/errors in the code.
Which block is optional?
Both catch and finally blocks are optional. A try block can exist either with one or more catch blocks
or a finally block or with both catch and finally blocks. A try block cannot exist without either catch
block or finally block.
Can we have try block without catch?
Yes, we can write try { } finally { } block.
Can we use multiple catch blocks with a try block?
Yes, we can.
Why we need finally block?
The finally block is used to clean any resource that is allocated in the try block. This block is always
executed even if an exception occurred or not occurred in try block. But the finally block does not
executed, when we write System.Environment.Exit(0) in either try or catch, the CLR is going to be
shutdown.
Can multiple catch blocks be executed?
No, multiple catch blocks can’t be executed. If a try block have more than one catch blocks, once the
proper catch code executed, the control is transferred to the finally block.
Can we write return statement in try catch or finally block?
Yes, we can write the return statement in try catch & finally.
What is difference between the “throw” and “throw ex” in .NET?
“Throw” statement provides details information and “Throw ex” statement provides short informaion.
“Throw” statement preserves original error stack whereas “throw ex” have the stack trace from their
throw point. It is always advised to use “throw” because it provides more accurate error information.

What is attribute in C#?


An attributes is a declarative tag that is used to convey information about the behaviors of various
elements (classes, methods, assemblies, structures, enumerators, etc). it is access at compile time
or run-time. Attributes are declare with a square brackets [] which is places above the elements.
[Obsolete(“Don’t use Old method, please use New method”, true)]

For example consider the bellow class. If we call the old method it will through error message.

public class myClass

[Obsolete("Don't use Old method, please use New method", true)]

public string Old() { return "Old"; }

public string New() { return "New"; }

myClass omyClass = new myClass();

omyClass.Old();

Why attributes are used?


In a program the attributes are used for adding metadata, like compiler instruction or other
information (comments, description, etc).
What are the types of attributes?
The Microsoft .Net Framework provides two types of attributes: the pre-defined attributes and
custom built attributes. Pre-define attributes are three types:
o AttributeUsage
o Conditional
o Obsolete
This marks a program that some entity should not be used.
What is custom attributes?
The Microsoft .Net Framework allows creating custom attributes that can be used to store
declarative information and can be retrieved at run-time.
What is Reflection?
Reflection is a process by which a computer program can monitor and modify its own structure and
behavior. It is a way to explore the structure of assemblies at run time (classes, resources,
methods). Reflection is the capability to find out the information about objects, metadata, and
application details (assemblies) at run-time. We need to include System.Reflection namespace to
perform reflections in C#. For example consider the following C# codes, which will returns some
meta information’s.
public class MyClass

public virtual int Add(int numb1, int numb2)

return numb1 + numb2;

public virtual int Subtract(int numb1, int numb2)

return numb1 - numb2;

static void Main(string[] args)

MyClass oMyClass = new MyClass();

//Type information.

Type oMyType = oMyClass.GetType();


//Method information.

MethodInfo oMyMethodInfo = oMyType.GetMethod("Subtract");

Console.WriteLine("\nType information:" + oMyType.FullName);

Console.WriteLine("\nMethod info:" + oMyMethodInfo.Name);

Console.Read();

Why we need reflection in c#


Reflections needed when we want to determine / inspect contents of an assembly. For example: at
Visual Studio editor intelligence, when we type “.” (dot) before any object, it gives us all the members
of the object. This is possible for Reflection. Beside this we need reflection for the following
purposes:
o To view attribute information at run time
o To view the structure of assemblies at run time (classes, resources, methods)
o It allows dynamic/late binding to methods and properties
o In serialization, it is used to serialize and de-serialize objects
o In web service, it is used to create and consume SOAP messages and also to generate WSDL
o Debugging tools can use reflection to examine the state of an object
What is dynamic keyword?
The dynamic is a keyword which was introduced in .NET 4.0. Computer programming languages are
two types: strongly typed and dynamically typed. In strongly types all types checks are happened at
compile time, in dynamic types all types of checks are happened at run time.
For example consider the following code
dynamic x = "c#";

x++;

It will not provide error at compile time but will provide error at run time.

When to use dynamic?


The biggest practical use of the dynamic keyword is when we operate on MS Office.
What is the difference between reflection and dynamic?
Both Reflection and dynamic are used to operate on an object during run time. But they have some
differences:
o Dynamic uses reflection internally
o Reflection can invoke both public and private members of an object. But dynamic can only invoke public
members of an object
What is serialization?
When we want to transport an object through network then we need to convert the object into a
stream of bytes. Serialization is a process to convert a complex objects into stream of bytes for
storage (database, file, cache, etc) or transfer. Its main purpose is to save the state of an object.
De-serialization is the reverse process of creating an object from a stream of bytes to their original
form.
What are the types of serialization?
The types of Serializations are given bellow:
o Binary Serialization
In this process all the public, private, read only members are serialized and convert into stream of bytes.
This is used when we want a complete conversion of our objects.
o SOAP Serialization
In this process only public members are converted into SOAP format. This is used in web services.
o XML Serialization
In this process only public members are converted into XML. This is a custom serialization. Required
namespaces: System.Xml, System.Xml.Serialization.
Why serialization and de-serialization?
For example consider, we have a very complex object and we need XML format to show it on HTML
page. Then we can create a XML file in the disk, writes all the necessary data on the XML file, and
use it for the HTML page. But this is not good approach for large number of users. Extra space is
required; anyone can see the XML file which creates security issue. We can overcome it by using
XML serialization.
When to use serialization?
Serialization is used in the following purposes:
o To pass an object from on application to another
o In SOAP based web services
o To transfer data through cross platforms, cross devices
Give examples where serialization is used?
Serialization is used to save session state in ASP.NET applications, to copy objects to the clipboard
in Windows Forms. It is also used to pass objects from one application domain to another. Web
services uses serialization.
What is Generics?
Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that
allows us to write codes that works for any data types.
What is a generic class?
A generic class is a special kind of class that can handle any types of data. We specify the data
types during the object creations of that class. It is declared with the bracket <>. For example
consider the following Comparer class, which has a method that compare two value and returns as
Boolean output.
public class Comparer<Unknown>

public bool Compare(Unknown t1, Unknown t2)

if (t1.Equals(t2))

return true;
}

else

return false;

Comparer<int> oComparerInt = new Comparer<int>();

Console.WriteLine(oComparerInt.Compare(10, 10));

Comparer<string> oComparerStr = new Comparer<string>();

Console.WriteLine(oComparerStr.Compare("jdhsjhds", "10"));

Why we should use generics?


Generic provides lot of advantages during programming. We should use generics for the following
reasons:
o It allows creating class, methods which are type-safe
o It is faster. Because it reduce boxing/un-boxing
o It increase the code performance
o It helps to maximize code reuse, and type safety
What is Collections in C#?
Sometimes we need to work with related objects for data storage and retrieval. There are two ways
to work with related objects. One is array and another one is collections. Arrays are most useful for
creating and working with a fixed number of strongly-typed objects. Collections are enhancement of
array which provides a more flexible way to work with groups of objects.
The Microsoft .NET framework provides specialized classes for data storage and retrieval.
Collections are one of them. Collection is a data structure that holds data in different ways.
Collections are two types. One is standard collections, which is found under System.Collections
namespace and another one is generic collections, which is found under System.Collections.Generic
namespace.The generic collections are more flexible and preferable to work with data.
Some commonly used collections under System.Collections namespace are given bellow:

o ArrayList
o SortedList
o Hashtable
o Stack
o Queue
o BitArray
What is unsafe code?
In order to maintain security and type safety, C# does not support pointer generally. But by using
unsafe keyword we can define an unsafe context in which pointer can be used. The unsafe code or
unmanaged code is a code block that uses a pointer variable.
In the CLR, unsafe code is referred to as unverifiable code. In C#, the unsafe code is not necessarily
dangerous. The CLR does not verify its safety. The CLR will only execute the unsafe code if it is
within a fully trusted assembly. If we use unsafe code, it is our own responsibility to ensure that the
code does not introduce security risks or pointer errors.

What are the properties of unsafe code?


Some properties of unsafe codes are given bellow:
o We can define Methods, types, and code blocks as unsafe
o In some cases, unsafe code may increase the application’s performance by removing array bounds checks
o Unsafe code is required in order to call native functions that require pointers
o Using unsafe code brings security and stability risks
o In order to compile unsafe code, the application must be compiled with /unsafe
Can unsafe code be executed in un-trusted environment?
Unsafe code cannot be executed in an un-trusted environment. For example, we cannot run unsafe
code directly from the Internet.
How to compile unsafe code?
For compiling unsafe code, we have to specify the /unsafe command-line switch with command-line
compiler. For example, to compile a program named “myClass.cs” containing unsafe code the
command line command is:
csc /unsafe myClass.cs

In Visual Studio IDE at first we need to enable use of unsafe code in the project properties. The
steps are given bellow:

o Open project properties


o Click on the Build tab
o Select the option “Allow unsafe code”
What is Pointer?
Pointer is a variable that stores the memory address of another variable. Pointers in C# have the
same capabilities as in C or C++. Some examples are given bellow:
int *i // pointer of an integer

float *f // pointer to a float

double *d // pointer to a double

char *ch // pointer to a character

Should I use unsafe code in C#?


In C#, pointer is really used and Microsoft disengaged to use it. But there are some situations that
require pointer. We can use pointer if required at our own risk. Some sonorous are given bellow:
o To deal with existing structures on disk
o Some advanced COM or Platform Invoke scenarios that involve pointer
o To performance critical codes

Potrebbero piacerti anche