0% found this document useful (0 votes)
133 views

Basics

Partial methods must return void and use the partial keyword. Value types cannot be inherited from or be null. Value types are initialized to their default values. A variable of a value type always refers to an instance of that type, unlike reference types.

Uploaded by

nagaraja h i
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Basics

Partial methods must return void and use the partial keyword. Value types cannot be inherited from or be null. Value types are initialized to their default values. A variable of a value type always refers to an instance of that type, unlike reference types.

Uploaded by

nagaraja h i
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 23

convert char array to string

string result = new string(CharArr);

----------------------------------
Many classes can implement a particular interface method, in their own way
An interface may inherit from multiple base interfaces
A class may implement-inherit from multiple interfaces
A C# class may only inherit from one class
--------------------------------------
Partial methods must use the partial keyword and must return void.
Value types are implicitly sealed (it is not possible to derive from a value type).
Value types can not be null.
Value types are given a default constructor that initialzes the value type to its
default value.
A variable of a value type is always a value of that type. Contrast this with
classes where a variable of type A could refer to a instance of type B if B derives
from A.
--------------------------------------
Partial methods can have in or ref but not out parameters.
Partial methods are implicitly private methods, so cannot be virtual.
Partial methods can be static methods.
Partial methods can be generic.

private-constructor

https://www.interviewsansar.com/use-of-private-constructor-in-csharp-example/
--------------------------------------
class: internal
struct: internal
method: private
members : private (i,e:for nested class, class, struct)
members (of interface or enum): public
constructor: private (note that if no constructor is explicitly defined, a public
default constructor will be automatically defined)
delegate: internal
interface: internal

constructor : private
public: Access is not restricted.
protected: Access is limited to the containing class or types derived from the
containing class.
internal: Access is limited to the current assembly.
protected internal: Access is limited to the current assembly or types derived
from the containing class.
private: Access is limited to the containing type.
private protected: Access is limited to the containing class or types derived
from the containing class within the current assembly.

-------------------------------------
String a = "TECHBEAMERS";
String b = "TECHBEAMERS";
String e = "TechBeamers";

int c;
c = a.CompareTo(b); //c=0
c = a.CompareTo(e);//c=-1
-----------------------------------
Console.WriteLine("30"+25+20); // o/p: 302520
Console.WriteLine(25 + 20+ "30");// o/p:4530
------------------------------------
Const: Const is nothing but "constant", a variable of which the value is constant
but at compile time. And it's mandatory to assign a value to it.
By default a const is static and we cannot change the value of a const variable
throughout the entire program.Readonly : Readonly is the keyword whose
value we can change during runtime or we can assign it at run time but only
through the non-static constructor. Not even a method. Readonly can set
value in non static constructor Static ReadOnly: A Static Readonly type variable's
value can be assigned at runtime or assigned at compile time and
changed at runtime. But this variable's value can only be changed in the static
constructor. And cannot be changed further. It can change only once at runtime.
---------------------
NNEW keyword used for creating the new object for the class and hiding the member
of parent class in child if it is intended
-----------------------------------
three ways to pass a parameter to a method in C#.
1.Value Parameters 2. Reference Parameters 3. Output Parameters
---------------------------------------
throw reset the stack trace so we can get line number of error .by using throw we
can get all exception information.but throw ex does not reset stack
trace so that's why it will give only original information of exception.
we can use await in catch and finally blocks in the latest version.
this keyword denote instance.....and static method does not support instance
can Create The static Constructor Of Static Class but not instance constructor
------------------------------------------------------------------------------
declare Obsolete attribute before the method eg.

[Obsolete]
public void Obsoletedemo()
{
}
or
[Obsolete message="Obsoletedemo"]
public void Obsoletedemo()
{
}
------------------------------------------------------------------------------
Two thing to notice about private constructor :1. Class with private constructor
can not be inherited 2. We can not create object of the class which
has private constructor Use of Private constructor: Many times we do not want
create instance of some of the classes like Helper, utility and common routine
classes.
----------------
Static Method Cannot Be Override ,Because Static Method is not virtual method. if
We are trying to do this will throw run time error like "An object
reference is required for the non-static field, method, or property
'Rextester.one.firstp.get'"
abstract class can have Static Methods. The reason for this is Static methods do
not work on the instance of the class, they are directly associated
with the class itself. So if you write a static method in the class and compile it,
and when you try to view the IL, it will be same as any other class accessing the
static member.

We cant declare fields inside the Interface. Note : We can declare abstract
properties and functions inside Interface.

Enums cannot inherit from other enums. In fact all enums must actually inherit
from System.Enum .Enums are by default sealed. So, we cant inherit.
static classes are sealed classes , they can not be inherit. It has public static
members that you can always access via the class name itself.
The main purpose of the static class is to create only one istance of the member in
the memory.
---------------------------------------
DateTime CAN be compared to null; It cannot hold null value, thus the comparison
will always be false
DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by
making them to "Nullable" type, We can set to null.
---------------------------------------
.net run time tries to find the requested result as earliest and returns it back
the caller. This is called short-circuiting.
As soon as any statement expression is true , runtime returns that value as
response and hence short-circuiting the request pipeline.

Ex:-

if(statement 1){
return 1;
}
else if( statement 2){
return 2;
}
else{
return 3;
}

--------------------------------------
Static constructors are used to initializing the static members of the class and
implicitly called before the creation of the first instance of the
class. Non-static constructors are used to initializing the non-static members of
the class.Non-static constructors can also be called as Instance Constructors as
they need instance to get executed.
Static constructors must be parameterless since it is not invoked by creating
object rather automatically called. 2 static constructor is not possible
since static constructor overloading is not possible as it does not allow
parameters
class Geeks {
// static variable
static int staticval;

// non-static variable
int val;

// declaration of
// static constructor
static Geeks()
{ staticval=1;
val=10; //error!! non static member inside static constructor
Console.WriteLine("It is static constructor");
}

// declaration of
// non-static constructor
Geeks()
{ staticval=1; //feasible
val=10; //feasible
Console.WriteLine("It is non-static constructor");
}
---------------
Why interface cannot have static methods
why Static classes cannot implement an interface
----------------------------
we cant change the name of webconfig file.The default value of int type is zero
----------------------------
try
{

finally
{

}
this is possible
----------------
try
{

}
not possible
---------------------
public TicketingKeyController()
{
Console.WriteLine("Hello! Constructor 1");
}

// Constructor with parameter


// Here this keyword is used
// to call Geek constructor
public TicketingKeyController(int a)
: this() //will call the constructor of the same clss with no parameter;
this("abc") will call constructor with string as parameter
{
Console.WriteLine("Hello! Constructor 2");
}

TicketingKeyController ticketingKeyController = new TicketingKeyController(1);


o/p:
"Hello! Constructor 1"
"Hello! Constructor 2"
--------------------
public int Add(int a, int b)
{

return 1;
}
public String Add(int a, int b) //compile time error
{
return "1";
}

------------------------
Class Shape1
{
public void CalculateArea()
{
//
}
}

There is another class shape2 that one also has same method
Class Shape2
{
public void CalculateArea()
{
//
}
}

Now i have a child class Circle, it derives from both SHape1 and shape2;

public class Circle: Shape1,shape2


{
}

Now when i create object for Circle, and call the method, system doesnt know which
calculate area method to be called.. Both has same signatures.
So compiler will get confuse .thats why multiple inheritances are not allowed.

But there can be multiple interfaces because interfaces dont ve methjod


definition..Even both the interfaces have same method, both of them dont ve any
implementation and always method in the child class will be executed..
---------------------------------------
You can use multiple catch block for one try block. but there can be only one try
block for a single code block.but only the one that first matches the exception
type is executed. That means you need to order the catch blocks properly.

try
{

}
catch (Exception) //exception handle is done here
{

throw;
}
catch
{

throw;
}
--------------------------------
const(satic by default) should be initialized with value during the declaration;
once assigned a value , no where it can be modified
const val=100;

readonly field can be initialized only during declaration or in constructor;

copy of static fields are created only once even if multiple instance are created
-------------------------------
Anonymous Types:temporary data type which is inferred based on the data that you
insert in an object initializer.
It is derived from System.Object class and it is also a sealed class. So, the
properties of anonymous type are read-only means you cannot change their values.
It also has intellisense support in Visual Studio.It is of reference type.It cannot
be cast to any other type except an object.
The scope of the anonymous type is always limited to the method in which they are
defined. Due to their local scope, you are not allowed to pass an anonymous type
to another method, but you can pass it to those methods which can accept dynamic
type parameters.
var any_object = new {id = 134,
name = "Siya",
language = "Ruby"
};
--------------------------------
Only one copy of static member is created regardless of how many instance of class
is created . This will work fine if your application is single user
but for multiple user if uses same class then this static member will create
problem as it will not reset the value for different user session and will
assign the value which is used by previous session user .So while having multiple
session in your application use static keyword wisely
-------------------------------
cross-page-posting
https://www.c-sharpcorner.com/blogs/what-is-cross-page-posting-in-asp-net
Cross-Site Scripting (XSS) Attack And Its Prevention Mechanism
------------------------------
How can we access base class constructor from a derived class constructor in C#?
-----------------------------

---------------------------------
public int MultipleReturns(int a, int b, ref/out int max)
{
if(a<b)
{
max=a;
return b;
}
else
{
max=b;
return a;
}
}
ref/out parameters do not work if you plan to use async/await functionality
Returning an object of Class/Struct Type
Returning Arrays
Returning a Tuple: return new Tuple<int, int>(min, max);

-------------------------
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();

Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

------------------------
why we need inheritance

--------------------
The continue statement skips the current iteration and moves to next iteration
for(int i=0; 1<5; i++)
{
if(i==3)
{
continue;
}
Console.WriteLine(i.ToString());
}

Output:
1
2
4
5
-------------------------------------
var val = Convert.ToInt32(null); //0
var b = int.Parse(null); //error Value cannot be null.
var c = int.TryParse(null,out int result); c=false ,result=0
https://www.c-sharpcorner.com/article/uses-of-int-parse-convert-toint-and-int-
tryparse/
---------------------
app.config file is not compulsory in .net application
------------------------------------------------
The [Flag] attribute is used when Enum represents a collection of multiple possible
values rather than a single value.
------------------------------------------------
Is Operator is used to Check the Compatibility of an Object with a given Type and
it returns the result as a Boolean.
var obj=.....;
if(obj is int)
{
...
}

As Operator is used for Casting of Object to a given Type or a Class. The as


keyword is used to cast nullable types if the specified value is not an
instance of the specified type.
AnyClass anyObject = obj as AnyClass;

----------------------------------------------
The C# method parameter limit is 65,535. Most browsers only support an URL of 2000
to 4000 characters.

-----------------------------
derived_class b = new base_class(); //not possible
base_class b = new derived_class(); //possible and b.method will call the methods
of derived_class

--------------------
Mock<IOptions<AppSettings>> appSettings = null;
private Mock<ITrxSyncDAL<ClosedLoopTrxItem>> ClosedLoopTrxSyncDAL = null;
private Mock<ILogger> logger = null;

public ClosedLoopDeviceTransactionSyncTest()
{
ClosedLoopTrxSyncDAL = new Mock<ITrxSyncDAL<ClosedLoopTrxItem>>();
appSettings = new Mock<IOptions<AppSettings>>();
logger = new Mock<ILogger>();
}

var istrxValid = Controller.Setup(post => post.InsertTransaction(dt,


transactionItems)).Returns(errorType);

var istrxInsertion = Controller.Object.InsertTransaction(dt, transactionItems);


var controller = new Controller(appSettings.Object, new
SyncBLL<TrxItem>(appSettings.Object, logger.Object, BAL.Object), logger.Object);

var result = controller.Service(TrxList);

Tight Coupling: When a class is dependent on a concrete dependency, it is said to


be tightly coupled to that class. A tightly coupled object is dependent
on another object; that means changing one object in a tightly coupled application
often requires changes to a number of other objects. It is not
difficult when an application is small but in an enterprise level application it
is too difficult to make the changes.

Loose Coupling: It means two objects are independent and an object can use another
object without being dependent on it. It is a design goal that seeks to reduce the
inter- dependencies among components of a system with the goal of reducing the risk
that changes in one component will require changes in any other component.
---------------------
Console.Read() - reads the first charater from the i/p stream and gives only the
ASCII Value of it. Returns (-1) if there is no more character to be read
Console.ReadKey() - expects single character only and give key- E and keychar -
101'e' FOR e
Console.ReadLine() -- Reads stream of character and assigns it to a var

Console.Write("Table");
Console.Write("chair");
Console.WriteLine();
Console.WriteLine("desk");

O/P:
Tablechair
desk

--------
var val1=Console.Read()
var val2=Console.ReadLine()

i/p:
abcd
val1=97
val2=abcd

----------------
https://www.careerride.com/
https://www.sanfoundry.com/object-oriented-programming-questions-answers-
constructors/
https://brainly.in/question/
-----------------------------------
Exception Description
System.DivideByZeroException handles the error generated by dividing a number with
zero.
System.NullReferenceException handles the error generated by referencing the null
object.
System.InvalidCastException handles the error generated by invalid
typecasting.
System.IO.IOException handles the Input Output errors.
System.FieldAccessException handles the error generated by invalid private or
protected field access.
-----------------------------------

ineligible:
Console.WriteLine("You are not eligible to vote!");

Console.WriteLine("Enter your age:\n");


int age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
goto ineligible;
}
else
{
Console.WriteLine("You are eligible to vote!");

o/p:
"You are not eligible to vote!"
Enter your age: 12
You are not eligible to vote!
Enter your age: 54
You are eligible to vote!
-----------------------------------
class

public int MyProperty;


public static int MyStaticProperty;

static User()
{
MyProperty=2; //not allowed
MyStaticProperty=4;
Console.WriteLine("I am Static Constructor");
}

// Default Constructor

public User()
{
MyStaticProperty=2 //not allowed
MyProperty=1;
Console.WriteLine("I am Default Constructor");
}

User user = new User(); // static and default constructor will be invoked
var prop=user.MyProperty; //valid
var statpropName=MyStaticProperty; //not valid
// Only Default constructor will be invoked

User user1 = new User();

Console.WriteLine("\nPress Enter Key to Exit..");

Console.ReadLine();

O/P:
I am Static Constructor
I am Default Constructor
I am Default Constructor

C# static constructor is used to initialize static fields. It can also be used to


perform any action that is to be performed only once. It is invoked automatically
before
first instance is created or any static member is referenced.
C# static constructor cannot have/accept any modifier or parameter(parameter
less).A static constructor must be parameterless because nothing ever calls it, it
is invoked
when you access a static member or create an instance of the class, but not
directly (it is called by the runtime).
C# static constructor is invoked implicitly whenever we create the first instance
of a class. It can't be called explicitly.
The static constructor will be invoked by CLR so we don’t have a control on static
constructor execution order in c#.
In c#, only one static constructor is allowed to create.
----------------------------------

params is a keyword which is used to specify a parameter that takes variable number
of arguments. It is useful when we don't know the number of arguments prior. Only
one
params keyword is allowed and no additional parameter is permitted after params
keyword in a function declaration.
public void Show(params int[] val) // Params Paramater
{
for (int i=0; i<val.Length; i++)
{
Console.WriteLine(val[i]);
}
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(2,4,6,8,10,12,14); // Passing arguments of variable length

}
-----------------------------------
The C# break is used to break loop or switch statement. It breaks the current flow
of the program at the given condition. In case of inner loop, it breaks only inner
loop.

for (int i = 1; i <= 10; i++)


{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}

O/P 1 2 3 4
------------------------------------

for(int i=1;i<=5;i++)
{
if(i==3)
{
continue;
}
Console.WriteLine(i);
}
O/P 1 2 4
------------------------------------
public static void Main(string[] args)
{
ineligible:
Console.WriteLine("You are not eligible to vote!");

Console.WriteLine("Enter your age:\n");


int age = Convert.ToInt32(Console.ReadLine());
if (age < 18){
goto ineligible;
}
else
{
Console.WriteLine("You are eligible to vote!");
}
}

------------------------------------
In C#, base keyword is used to access fields, constructors and methods of base
class.

You can use base keyword within instance method, constructor or instance property
accessor only. You can't use it inside the static method.
We can use the base keyword to access the fields of the base class within derived
class. It is useful if base and derived classes have the same fields.
If derived class doesn't define same field, there is no need to use base keyword.
Base class field can be directly accessed by the derived class.
------------------------------------
An assembly((IL, Metadata, and Manifest) in a single package is a file that is
automatically generated by the compiler upon successful compilation of every .NET
application. It can be either a
Dynamic Link Library or an executable file. It is generated only once for an
application and upon each subsequent compilation the assembly gets updated.
An Assembly contains Intermediate Language (IL) code, which is similar to Java byte
code. In the .NET language, it consists of metadata
------------------------------------
Extension methods helps to add new methods to the existing type(class) without
modifying the original code , inheriting or aggregating

public class Maths


{

public void Sub(int a, int b)


{
return a+b;
}
}

using Maths;
public static void SomeMoreMtahs
{

public void Subract(this Maths obj,int a, int b)


{
return a-b;
}
}

static void Main()

static class are sealed.

boxing and unboxing


int Val = 1;
Object Obj = Val; //Boxing

int Val = 1;
Object Obj = Val; //Boxing
int i = (int)Obj; //Unboxing

--------------
Object Pooling
Anonymous Types In C#
----------------
static Random random = new Random();
random.Next();
random.Next(10,20);

------------------------------
Differences Between Task And Thread
Task is more abstract then threads. It is always advised to use tasks instead of
thread as it is created on the thread pool which has already system created threads
to improve the performance.

The task can return a result. There is no direct mechanism to return the result
from a thread.

Task supports cancellation through the use of cancellation tokens. But Thread
doesn't.
A task can have multiple processes happening at the same time. Threads can only
have one task running at a time.

You can attach task to the parent task, thus you can decide whether the parent or
the child will exist first.

While using thread if we get the exception in the long running method it is not
possible to catch the exception in the parent function but the same can be easily
caught if we are using tasks.

You can easily build chains of tasks. You can specify when a task should start
after the previous task and you can specify if there should be a synchronization
context switch. That gives you the great opportunity to run a long running task in
background and after that a UI refreshing task on the UI thread.

A task is by default a background task. You cannot have a foreground task. On the
other hand a thread can be background or foreground.

The default TaskScheduler will use thread pooling, so some Tasks may not start
until other pending Tasks have completed. If you use Thread directly, every use
will start a new Thread.

-----------------------------------------------------------------------------------
--------------------------------------------------

Clean Solution - deletes all compiled files (all dll’s and exe’s ) from directories
(bin and obj) .
Build Solution - compiles code files (dll and exe) that have changed.Incremental
build
Rebuild Solution - Deletes all compiled files and Compiles them again regardless of
whether or not the code has changed.

REBUILD- CLEAN PROJECT1 >>>BUILD PROJECT1>>CLEAN PROJECT2 >>>BUILD PROJECT2

clean+BUILD- CLEAN PROJECT1>>> CLEAN PROJECT2 >>>BUILD PROJECT1>>BUILD PROJECT2

-----------------------------------------------------------------------------------
--------------------------------------------------

Abstract Class and Interface

An abstract class cannot support multiple inheritance, but an interface can support
multiple inheritance. Thus a class may inherit several interfaces
but only one abstract class.

An interface is an empty shell, just only the signatures of the methods. The
methods do not contain anything. The interface can't do anything.
It's just a pattern. An Abstract class is a class which will contains both
definition and implementation in it.

Abstract classes can have consts, members, method stubs and defined methods,
whereas interfaces can only have consts and methods.

Various access modifiers such as abstract, protected, internal, public, virtual,


etc. are useful in abstract Classes but all methods of an interface
must be defined as public.

A child class can define abstract methods with the same or less restrictive
visibility, whereas a class implementing an interface must define the methods
with the exact same visibility.

If we add a new method to an Interface then we have to track down all the
implementations of the interface and define implementation for the new method.
But if we add a new method to an abstract class then we have the option of
providing default implementation and therefore all the existing code might
work properly.
-----------------------------------------------------------------------------------
--------------------------------------------------
.EXE
.DLL
An exe always runs in its own address space i.e It is a separate process. A dll
always needs a host exe to run. i.e., it can never run in its own address space. A
DLL would share the same process and memory space of the calling application
The purpose of an EXE is to launch a separate application of its own. The
purpose of a DLL is to have a collection of methods/classes which can be re-used
from
some
other application.

Only for specific purpose . They can


be reused for some other application. As long as the coder
knows
the names and parameters of the functions and procedures in the DLL file

An EXE is a program that can be executed . Ex :Windows program DLLs are


not directly executable . They are separate files containing functions that can be

called by programs and other DLLs to perform


computations and functions.

Does not contain an entry point (no main function) so can not run individually
Contains an entry point (Main function) so can run individually
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------------
Difference between a Debug and Release build

The Release mode enables optimizations and generates without any debug data, so it
is fully optimized. . Lots of your code could be completely removed
or rewritten in Release mode. The resulting executable will most likely not match
up with your written code. Because of this release mode will run faster
than debug mode due to the optimizations.

.Net project. Programmers generally use the Debug mode for debugging step by step
their .Net project and select the Release mode for the final build of
Assembly file (.dll or .exe).

The Debug mode does not optimize the binary it produces because the relationship
between source code and generated instructions is more complex.
This allows breakpoints to be set accurately and allows a programmer to step
through the code one line at a time. The Debug configuration of your
program is compiled with full symbolic debug information which help the debugger
figure out where it is in the source code.

Debug information can be generated in a .pdb (Program Database File) file depending
on the compiler options that are used. A .pdb file holds debugging
and project state information that allows incremental linking of a Debug
configuration of your program. A Program Database File is created when you compile
C# program with debug mode.
-----------------------------------------------------------------------------------
--------------------------------------------------------------------------------

Truncate A Table Using Entity Data Model


using (var context = new MyTestDbEntities())

context.ExecuteStoreCommand("TRUNCATE table Dummy");

}
-----------------------------------------------------------------------------------
--------------------------------------------------
disable the lazy loading by
context.ContextOptions.LazyLoadingEnabled = false;
-----------------------------------------------------------------------------------
---------------------------------------------------------------------------
inheritance:
Adv of Inheritence : The reuse of existing classes saves time and effort. When you
create a class to derive from another class, the inherited class
implicitly gains all the data and functionality of the base class, except for its
constructors and destructors.

Multiple inheritance types:


Single Inheritance
Multi Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multipath inheritance
Multiple Inheritance

interface X
{ }
interface Y
{ }

class NewClass : X, Y { }
class NewClass : FirstClass, X
{ }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
Class Shape1
{
public void CalculateArea()
{
//
}
}

There is another class shape2 that one also has same method
Class Shape2
{
public void CalculateArea()
{
//
}
}
Now i have a child class Circle, it derives from both SHape1 and shape2;

public class Circle: Shape1,shape2


{
}

Now when i create object for Circle, and call the method, system doesnt know which
calculate area method to be called.. Both has same signatures.
So compiler will get confuse .thats why multiple inheritances are not allowed.

But there can be multiple interfaces because interfaces dont ve methjod


definition..Even both the interfaces have same method, both of them dont have
any implementation and always method in the child class will be executed.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
class a
{
method1()
{
}
}

class b : class a
{
method1()
{
//abc
}
}

class c :class a
{
method1()
{
//cde
}
}

class d: class b, class c


{
method2()
{
class a =new class a();
a.method1(); //which method will be call here? class c or class b?
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
"finally" block in C
The execution of a finally block is intended to release resources , such as
database connections that are allocated in a try block,
and you can run code even if an exception occurs in the try block .finally block
MUST NOT throw an exception unless the system design explicitly wants
you to do so, which is considered bad practice in general. C# also contains the
using statement , which provides same functionality for IDisposable objects in a
convenient manner.
var connection = new SqlConnection();
connection.Open()
try
{
// execute a command
}
catch
{
// handle an exception
}
finally
{
// do any required cleanup
// if the code executes with or without an exception, we have to close
connection here
connection.Close();
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
The Clone() method returns a new array object containing all the elements in the
original array. This method creates a copy of an array as an object,
therefore needs to be cast to the actual array type before it can be used to do
very much. The clone is of the same Type as the original Array.

The CopyTo() method copies the elements into another existing array. It copies the
elements of one array to another pre-existing array starting from a
given index (usually 0).
Both perform a shallow copy . Shallow copying is creating a new object and then
copying the non static fields of the current object to the new object.
If the field is a value type, a bit by bit copy of the field is performed. If the
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. A shallow copy of an object is a new object whose instance
variables are identical to the old object.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------
Anonymous types are a feature of C# 3.0 , that allows data types to encapsulate a
set of properties into a single object without having to first
explicitly define a type. The type name is generated by the compiler and is not
available at the source code level. The type of each property is
inferred by the compiler. C# allows you to create an object with the new keyword
without defining its class.

Example
var student = new { Name= "John", Marks = 890, Passed = true };
Console.WriteLine(student.Name + student.Marks + student.Passed);

Anonymous types typically are used in the select clause of a query expression to
return a subset of the properties from each object in the source
sequence. LINQ queries use them a lot, for example:
var studentQuery =
from stud in students
select new { stud.Name, stud.Age };
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
Dynamic vs Object http://net-informations.com/faq/priq/type.htm
Object Pooling
Finalize() Vs Dispose() methods
Finally Block Exceptions:

Public static Void Main()


{
try
{
Hello();
}
catch(Exception ex)
{
Console.WriteLine(ex.message)
}
}
public static void Hello()
{
try
{
throw new exception("try block exception");
}
finally
{
throw new exception("finally block exception");
}
}

o/p: finally block exception


and try block exception is lost
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
static void Main(string[] args)
{
try
{
Method2();
}
catch (Exception ex)
{
Console.Write(ex.StackTrace.ToString()); //actual exception occured in
try block of Method1() but throw ex is used in Method2 catch block hence in
Console.ReadKey(); //stack trace shows the exception
would have appeared in Method2 try block
}
}

private static void Method2()


{
try
{
Method1();
}
catch (Exception ex)
{
//throw ex resets the stack trace Coming from Method 1 and propogates it to
the caller(Main)
throw ex;
}
}

private static void Method1()


{
try
{
throw new Exception("Inside Method1");
}
catch (Exception)
{
throw;
}
}

throw ex resets the stack trace (so your errors would appear to originate from
HandleException)
throw doesn't - the original offender would be preserved and preserves its original
stack trace.
https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-
throw-ex

-----------------------------------------------------------------------------------
-----------------------------------------------------------------

C# HashTable vs Dictionary vs ArrayList vs List


1 Dictionary 2.82 seconds
2 Hashtable 2.96 seconds
3 Array 4.68 seconds
4 List 15.75 seconds
5 ArrayList 30.08 seconds

HASHTABLE
DICTIONARY
A Hashtable is a non-generic collection.
A Dictionary is a generic collection.
Hashtable is defined under System.Collections namespace.
Dictionary is defined under System.Collections.Generic namespace.
In Hashtable, you can store key/value pairs of the same type or of the different
type. In Dictionary, you can store key/value pairs of same type.
In Hashtable, there is no need to specify the type of the key and value.
In Dictionary, you must specify the type of key and value.
The data retrieval is slower than Dictionary due to boxing/ unboxing.
The data retrieval is faster than Hashtable due to no boxing/ unboxing.
In Hashtable, if you try to access a key that doesn’t present in the given
Hashtable, In Dictionary, if you try to access a key that doesn’t present in the
given Dictionary, then it will give error.
then it will give null values.
It is thread safe.It is also thread safe but only for public static members.
It doesn’t maintain the order of stored values. It always maintain the order of
stored values.

Unlike arrays, Arraylist can have objects of different types.


/*Create a hash table*/
var hashTable = new Hashtable
{
{ "Tom", 32 },
{ "John", 22 }
};

/*Create a dictionary*/
var dict = new Dictionary<string, int>
{
{"Tom", 32},
{"John", 22},
};

/*Create an array*/
var array = new Person[5];
array[0] = new Person { Name = "Tom", Age = 32 };
array[1] = new Person { Name = "John", Age = 22 };

/*Create an arraylist */
var arraylistLst = new ArrayList
{
new Person {Name = "Tom", Age = 32},
new Person {Name = "John", Age = 22}
};

/*Create a List*/
var list = new List<Person>
{
new Person {Name = "Tom", Age = 32},
new Person {Name = "John", Age = 22}
};
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
VAR
DYNAMIC
The type of the variable is decided by the compiler at compile time. The type of
the variable is decided by the compiler at run time.

If the variable does not initialized it throw an error. If the


variable does not initialized it will not throw an error.

It support intelliSense in visual studio. It does not


support intelliSense in visual studio.

var myvalue = 10; // statement 1 dynamic


myvalue = 10; // statement 1
myvalue = “GeeksforGeeks”; // statement 2 myvalue =
“GeeksforGeeks”; // statement 2 Here, the compiler will not throw an
Here the compiler will throw an error because the compiler has already error
though the type of the myvalue is an integer. When you assign a string to myvalue
it
decided the type of the myvalue variable using statement 1 that is an recreates
the type of the myvalue and accepts string without any error.
integer type. When you try to assign a string to myvalue variable,
then the compiler will give an error because it violating safety rule type.

It cannot be used for properties or returning values from the function. It can
be used for properties or returning values from the function.
It can only used as a local variable in function.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------
MANAGED CODE
UNMANAGED CODE
It is executed by managed runtime environment or managed by the CLR. It is
executed directly by the operating system.
It provides security to the application written in .NET Framework. It
does not provide any security to the application.
Memory buffer overflow does not occur.
Memory buffer overflow may occur.
It provide runtime services like Garbage Collection, exception handling It
does not provide runtime services like Garbage Collection, exception handling, etc.
The source code is complied in the intermideate language know as IL or The
source code direclty compile into native langugae.
MSIL or CIL.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------
thread helps to run the codes parallely using context switching or time slicing
TPL will never do context switching

A system is said to be concurrent if it can support two or more actions in progress


at the same time. A system is said to be parallel if it can
support two or more actions executing simultaneously. The key concept and
difference between these definitions is the phrase “in progress.”

-----------------------------------------------------------------------------------
------------------------------------------------------------------
Struct vs Class

A structure is a value type so it is stored on the stack, but a class is a


reference type and is stored on the heap.

A structure doesn't support inheritance, and polymorphism, but a class supports


both.

By default, all the struct members are public but class members are by default
private in nature.

As a structure is a value type, we can't assign null to a struct object, but it is


not the case for a class.
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
+------------------------
+----------------------------------------------------------------------------------
--------------------
+----------------------------------------------------------------------------------
-----------------+
| | Struct
| Class
|
+------------------------
+----------------------------------------------------------------------------------
--------------------
+----------------------------------------------------------------------------------
-----------------+
| Type | Value-type
| Reference-type
|
| Where | On stack / Inline in containing type
| On Heap
|
| Deallocation | Stack unwinds / containing type gets deallocated
| Garbage Collected
|
| Arrays | Inline, elements are the actual instances of the value
type | Out of line, elements are just
references to instances of the reference type residing on the heap |
| Aldel Cost | Cheap allocation-deallocation
| Expensive allocation-deallocation
|
| Memory usage | Boxed when cast to a reference type or one of the
interfaces they implement, | No boxing-unboxing
|
| | Unboxed when cast back to value type
|
|
| | (Negative impact because boxes are objects that are
allocated on the heap and are garbage-collected) |
|
| Assignments | Copy entire data
| Copy the reference
|
| Change to an instance | Does not affect any of its copies
| Affect all references pointing to the instance
|
| Mutability | Should be immutable
| Mutable
|
| Population | In some situations
| Majority of types in a framework should be classes
|
| Lifetime | Short-lived
| Long-lived
|
| Destructor | Cannot have
| Can have
|
| Inheritance | Only from an interface
| Full support
|
| Polymorphism | No
| Yes
|
| Sealed | Yes
| When have sealed keyword
|
| Constructor | Can not have parameterless constructors but can have a
static paramless constructor | Any constructor
|
| Null-assignments | When marked with nullable question mark
| Yes (+ When marked with nullable question mark in C# 8+)
|
| Abstract | No
| When have abstract keyword
|
| Member Access Modifiers| public, private, internal
| public, protected, internal, protected internal, private protected

Although the CLR allows it, C# does not allow structs to have a default parameter
less constructor. The reason is that, for a value type, compilers by
default neither generate a default constructor, nor do they generate a call to the
default constructor. So, even if you happened to define a default
constructor, it will not be called and that will only confuse you. To avoid such
problems, the C# compiler disallows definition of a default
constructor by the user. And because it doesn't generate a default constructor, you
can't initialize fields when defining them.

----------------------

Once the proper catch section is executed the control goes finally to block. So
there will not
be any scenarios in which multiple catch blocks will be executed.

You might also like