Basics
Basics
----------------------------------
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");
}
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;
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.
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;
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)
{
...
}
----------------------------------------------
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>();
}
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!");
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
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
Console.ReadLine();
O/P:
I am Static Constructor
I am Default Constructor
I am Default Constructor
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.
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!");
------------------------------------
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
using Maths;
public static void SomeMoreMtahs
{
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.
-----------------------------------------------------------------------------------
--------------------------------------------------
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.
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.
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.
-----------------------------------------------------------------------------------
--------------------------------------------------------------------------------
}
-----------------------------------------------------------------------------------
--------------------------------------------------
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.
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;
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.
class b : class a
{
method1()
{
//abc
}
}
class c :class a
{
method1()
{
//cde
}
}
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:
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
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
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.
/*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.
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
-----------------------------------------------------------------------------------
------------------------------------------------------------------
Struct vs Class
By default, all the struct members are public but class members are by default
private in nature.
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.