Professional Documents
Culture Documents
Questions C#
Questions C#
o Console Application
o Windows Forms applications
o Windows Presentation Foundation (WPF) application
o Web applications (ASP.net applications)
o Web Services
o Windows Services
o Service oriented applications using Windows Communication Foundation(WCF)
o Workflow-enabled applications using Windows Workflow Foundation (WF)
.net framework contains a rich collection of classes that are readily available
for the developers such as working with files,data storage,input output
etc..The classes in Framework Class Library(FCL) are logically grouped under
various namespaces.
o Runtime Host
o Load the runtime environment into execution process of a .net
application
o Create an application domain in .net process
o Common Type System
Maintains data integrity across the code written in different .net compliant
programming languages.
o Cross-languate Interoperability
o Profiling
Enables you to use the profilers dynamically with the running process.After a
profiler performs all requested profiling tasks you can detach it.
o Garbage Collection
o Code Verification
Specifies that CLR enforces type safety and prevents a source code from
performing illegal operations
2 ("Hello",2);
1 Tuple<int,int,int> t = Tuple.Create<int,int,int>(2,4,5);
When a program starts, the system allocates some memory for the program to get
executed.
The program manipulates the object, and at some point the object may no longer be
needed.
When the object is no longer accessible to the program and becomes a candidate for
garbage collection.
There are two places in memory where the CLR stores items while your code
executes.
stack
heap
The stack keeps track of what’s executing in your code (like your local variables),
and the heap keeps track of your objects.
Value types can be stored on both the stack and the heap.
For an object on the heap, there is always a reference on the stack that points to it.
The garbage collector starts cleaning up only when there is not enough room on the
heap to construct a new object
The stack is automatically cleared at the end of a method. The CLR takes care of
this and you don’t have to worry about it.
The heap is managed by the garbage collector.
A weak reference permits the garbage collector to collect the object while still
allowing the application to access the object. A weak reference is valid only during
the indeterminate amount of time until the object is collected when no strong
references exist. When you use a weak reference, the application can still obtain a
strong reference to the object, which prevents it from being collected. However,
there is always the risk that the garbage collector will get to the object first before
a strong reference is re-established.
Weak references are useful for objects that use a lot of memory, but can be
recreated easily if they are reclaimed by garbage collection.
Stack roots. Stack variables provided by the just-in-time (JIT) compiler and stack
walker.
Garbage collection handles. Handles that point to managed objects and that can be
allocated by user code or by the common language runtime.
Static data. Static objects in application domains that could be referencing other
objects. Each application domain keeps track of its static objects.
This memory is called the managed heap, as opposed to a native heap in the
operating system.
There is a managed heap for each managed process. All threads in the process
allocate memory for objects on the same heap.
The heap is organized into generations so it can handle long-lived and short-lived
objects. Garbage collection primarily occurs with the reclamation of short-lived
objects that typically occupy only a small part of the heap. There are three
generations of objects on the heap:
Newly allocated objects form a new generation of objects and are implicitly
generation 0 collections, unless they are large objects, in which case they go on the
large object heap in a generation 2 collection.
Most objects are reclaimed for garbage collection in generation 0 and do not survive
to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer
between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-
lived object is an object in a server application that contains static data that is live
for the duration of the process.
The fixed statement prevents the garbage collector from relocating a movable
variable. The fixed statement is only permitted in an unsafe context.
And For Web application it works in “Server garbage collection” mode, which is
intended for server applications that need high throughput and scalability. Server
garbage collection can be non-concurrent or background.
Example
3 GC.Collect();
4 GC.WaitForPendingFinalizers();
5 File.Delete(“temp.dat”);
It makes no sense for the garbage collector to consider collecting stack memory
because the stack is not managed that way: Everything on the stack is considered to
be “in use.” And memory used by the stack is automatically reclaimed when you
return from method calls. Memory management of stack space is so simple, cheap
and easy that you wouldn’t want garbage collection to be involved.
1. What is REST?
Representational state transfer(REST) is an abstraction of architecture of world wide
web. REST is an architectural style to design networked application.REST makes
communication between remote computers easy by using the simple HTTP protocol
which support for CRUD (Create, Read, Update, and Delete) operations on the
server.
ex: CsharpStar.com/posts
ex: CsharpStar.com/posts/1053
1. GET retrieves it
2. DELETE destroys it
3. PUT replaces it or create if doesnot exists
2{
6}
Example:
1 using System;
5 {}
6 }
7 class Person {
10 {
11 set {
12 if ( value >= 19 && value <= 60 )
13 age = value;
14 else{
15 InvalidAgeException
17 throw expObj;
18 }
19 }
20 get {
21 return age;
22 }
23 }
24 }
25 class Test {
29 try {
35 }
36 catch(InvalidAgeException expObj){
37 Console.WriteLine( expObj.Message );
38 }
39 }
40 }
Abstract members:
An abstract member is a function member that is designed to be overridden.An
abstract member has the following characteristics:
Example:
2 {
3 public void IdentifyBase() // Normal method
4 {
6 }
8 }
10 {
12 {
14 } // abstract method
15 }
16 class Program
17 {
19 {
25 }
26 }
Output:
I am Abstract Class
I am Derived Class
Virtual Keyword in C# :
Let’s look at the below example with new keyword:
1 class MyBaseClass
2 {
4 {
6 }
7 }
9 {
11 {
13 }
14 }
15 class Program
16 {
18 {
23 }
24 }
Output:
This is derived class
This is base class
In the above example, Main creates an object of type MyDerivedClass and stores its
reference in variable derivedclass.Main also creates a variable of type MyBaseClass
and uses it to store a reference to the base class portion of the object.When the
Print method is called on each reference, the call invokes the implementation of the
method that the reference can see,producing differentoutput strings.
you saw that when you access an object of a derived class by using a reference to
the base class, you get only the members from the base class. Virtual methods allow
a reference to the base class to access “up into” the derived class.
You can use a reference to a base class to call a method in the derived class if the
following are true:
o The method in the derived class and the method in the base class each have
the same signature and return type.
o The method in the base class is labeled virtual.
o The method in the derived class is labeled override.
Syntax:
2{
4 ...
6{
1 class MyBaseClass
2 {
4 {
6 }
7 }
9 {
13 }
14 }
15 class Program
16 {
18 {
21 derivedclass.Print();
22 mybaseclass.Print();
23 }
24 }
Output:
This is the derived class.
This is the derived class.
When the Print method is called by using the reference to the base
class(mybaseclass),the method call is passed up to the derived class and executed,
because
Summary:
In this article, we have discussed:
Example
1 enum colors
2 {
3 Red = 1,
4 Blue = 2,
5 Yellow = 3,
6 Green = 4
7 };
1 class Program
2 {
8 myColors.ToString());
9 Console.ReadLine();
10 }
11 }
1 class Program
2 {
6 {
10 {
11 lstDays.Add(arr.GetValue(i).ToString());
12 }
13 }
14 }
Or
1 class Program
2 {
6 {
8 }
9 }
1 class Program
2 {
4 {
5 red,
6 blue,
7 green,
8 yellow
9 }
11 {
13 {
14 Console.WriteLine(iColor.ToString());
15 }
16 }
17 }
1 class Program
2 {
3 enum Days
4 {
5 Sunday = 1,
6 TuesDay = 2,
7 wednesday = 3
8 }
9 static void Main(string[] args)
10 {
12 Console.WriteLine(day);
13 }
14 }
or
1 class Program
2 {
3 enum Days
4 {
5 Sunday = 1,
6 TuesDay = 2,
7 wednesday = 3
8 }
10 {
12 Console.WriteLine(day);
13 }
14 }
15 //Output: wednesday
1 class Program
2 {
3 enum Colors
4 {
5 Blue = 1,
6 Red = 2,
7 Yellow = 3,
8 Pink = 4
9 }
11 {
13 Console.WriteLine(color);
14 }
15 }
16 //Output : 2
7.How to convert String to Enum in C#?
1 class Program
2 {
3 enum Colors
4 {
5 Blue,
6 Red,
7 Yellow,
8 Pink
9 }
11 {
15 if (newColor == Colors.Red)
16 {
17 Console.WriteLine(newColor.ToString());
18 }
19 }
20 }
8. How to use Enum in Switch case in C# ?
1 class Program
2 {
3 enum Colors
4 {
5 Blue,
6 Red,
7 Yellow,
8 Pink
9 }
11 {
13 switch (value)
14 {
15 case Colors.Blue:
16 Console.WriteLine("Color is Blue");
17 break;
18 case Colors.Red:
19 Console.WriteLine("Color is Red");
20 break;
21 case Colors.Yellow:
22 Console.WriteLine("Color is Yellow");
23 break;
24 }
25 }
26 }
1. How will you specify what version of the
framework your application is targeting?
You can define “targetFramework” in Web.config file to specify the framework
version. It is introduced in Asp.net 4.0
1 <?xml version="1.0"?>
2 <configuration>
3 <system.web>
5 </system.web>
6 </configuration>
Unicode is a standard that can handle characters for almost all modern languages
and even some ancient languages at the same time, as long as the client has fonts
for the particular language installed in his system
UTF:
Unicode assigns each character a unique number, or code point. It defines two
mapping methods, the UTF (Unicode Transformation Format) encodings, and the UCS
(Universal Character Set) encodings. Unicode-based encodings implement the
Unicode standard and include UTF-8, UTF-16 and UTF-32/UCS-4. They go beyond 8-
bits.
ASCII:
ANSI:
The important things you need to know about nullable type conversions are the
following:
For example, the following lines show conversion in both directions. In the first line,
a literal of type
int is implicitly converted to a value of type int? and is used to initialize the variable
of the nullable type.
In the second line, the variable is explicitly converted to its non-nullable version.
Notes:
o The difference between a regular static method and an extension method is
the special this keyword for the first argument.
o Extension method cannot be declared on a class or struct.
o It can also be declared on an interface (such as IEnumerable). Normally, an
interface wouldn’t have any implementation. With extension methods,
however, you can add methods that will be available on every concrete
implementation of the interface
o Language Integrated Query (LINQ) is one of the best examples of how you can
use this technique to enhance existing code.
o Standard Implementation
o Double checked locking
o Early Instance Creation
o Fully Lazy Instantiation
o Using Generics
o using Lazy<T> type
Throw Syntax:
1 try
2{
3 // do some operation that can fail
4}
6{
8 throw;
9}
Throw ex Syntax:
1 try
2 {
4 }
6 {
8 throw ex;
9 }
10 }
1. How to update web.config programatically?
This file is an XML file, and reading/writing XML is supported by .NET. You can
choose one of the method as per your requirement:
1 class Program
2 {
4 {
5 MySortedList list = new MySortedList();
6 list.Add(13);
7 list.Add(81);
8 list.Add(25);
9 list.Add(9);
10 list.Add(33);
11 list.Add(46);
12 list.Add(1);
14 {
15 Console.WriteLine(v);
16 }
17 Console.ReadLine();
18 }
19 }
20
21 class MySortedList
22 {
25 {
26 get { return items; }
28 }
29
31 {
33 if (index < 0)
34 index = ~index;
35
41 items = dupArray;
42
45 {
48 items[index] = value;
49 }
50 }
So when old application calls this method, method with 5 parameter will execute.
And method with 6 parameter will be used by new application. That way we can
provide backward compatibility to old application.
1. What is Satellite Assembly?
A satellite assembly is a compiled library (DLL) that contains “localizable” resources
specific to a given culture such as strings, bitmaps, etc. You are likely to use
satellite assemblies when creating a multilingual UI application.
int y = 20;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True
For Example:
StringBuilder s1 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));
Output:
False
True
In above example, s1 and s2 are different objects hence “==” returns false, but they
are equivalent hence “Equals()” method returns true. Remember there is an
exception of this rule, i.e. when you use “==” operator with string class it compares
value rather than identity.
For value comparison, with Value Type use “==” operator and use “Equals()” method
while performing value comparison with Reference Type.
o Each of the partial class declarations contains the declarations of some of the
class members.
o The partial class declarations of a class can be in the same file or in different
files.
o Each partial declaration must be labeled as partial class,in contrast to the
single keyword class.
Advantages of Partial Class:
By Using Partial Classes, multiple developer can work on the same class easily.
Partial classes are mainly used by code generator to keep different concerns
separate
you can also define Partial methods as well where a developer can simply define the
method and the other developer can implement that.
In C#, a nested type that is enclosed in a generic type cannot be instantiated unless types have
been assigned to the type parameters of all enclosing types
– It is achieved when a class is derived from another class in such a way that it
inherits all its members.
– It is called as Class Inheritance.
– In this, it uses ‘extends’ keyword in Java.
– The subclass is tightly coupled with superclass.
– If there is any changes to superclass will break the whole relationship.
Interface inheritance:
– It is achieved when a class inherits only the signatures of the functions from
another class.
– It is called as Type inheritance and also called as subtyping.
– In this, it uses ‘implements’ keyword in Java.
– It is used for code reuse and polymorphism.
– It reduces coupling and implementation dependencies.
1 //using tilde(~)
2 [Flags]
4 {
5 All = ~0,
6 None = 0,
7 Cash = 1,
8 Check = 2,
9 CreditCard = 4
10 }
11 //Alternative:
12 [Flags]
13 public enum PurchaseMethod
14 {
15 None = 0,
16 Cash = 1,
17 Check = 2,
18 CreditCard = 4,
20 }
1 class Employee
2{
3 public Employee()
4 {
6 }
7 public string Name { get; set; }
8}
For example, the following code shows class MyClass, with a nested class called
MyCounter.
2 {
3 class MyCounter // Nested class
4 {
5 ...
6 }
7 ...
8 }
It is good to use Nested types if it is only meant to be used as a helper for the
enclosing type.
3 myI4 = 10;
1 myI4: -1
2 myI4: 10
1. What are weakreferences in C#?How is it different
than StrongReferences
The garbage collector cannot collect an object in use by an application while the
application’s code can reach that object. The application is said to have a strong
reference to the object.
A weak reference permits the garbage collector to collect the object while still
allowing the application to access the object. A weak reference is valid only during
the indeterminate amount of time until the object is collected when no strong
references exist. When you use a weak reference, the application can still obtain a
strong reference to the object, which prevents it from being collected. However,
there is always the risk that the garbage collector will get to the object first before
a strong reference is re-established.
Weak references are useful for objects that use a lot of memory, but can be
recreated easily if they are reclaimed by garbage collection
semantically, ref provides both “in” and “out” functionality, whereas out only
provides “out” functionality.
You can read the difference between value type and reference type here.
Hashtable supports multiple reader threads with a single writer thread, while
Dictionary offers no thread safety. If you need thread safety with a generic
dictionary, you must implement your own synchronization.
– To represent a single set of data. For example, a tuple can represent a database
record, and its components can represent individual fields of the record.
– To provide easy access to, and manipulation of, a data set.
– To return multiple values from a method without using out parameters
– To pass multiple values to a method through a single parameter. For example, the
Thread.Start(Object) method has a single parameter that lets you supply one value
to the method that the thread executes at startup time. If you supply a Tuple object
as the method argument, you can supply the thread’s startup routine with three
items of data.
7. How can you create responsive UI without
impacting users?
You can create a responsive UI using multithreading. You can split the work into
small pieces and run it in background without impacting user.
3 GC.Collect();
4 GC.WaitForPendingFinalizers();
5 File.Delete(“temp.dat”);
1 [Obsolete]
4 //You can also cause the compilation to fail if the method is called from somewhere in code like this:
2 {
3 int local;
6 {
7 local = valIn * 2; // this will work fine
9 };
10
14 }
2 {
4 }
This memory is called the managed heap, as opposed to a native heap in the
operating system.
There is a managed heap for each managed process. All threads in the process
allocate memory for objects on the same heap.
The heap is organized into generations so it can handle long-lived and short-lived
objects. Garbage collection primarily occurs with the reclamation of short-lived
objects that typically occupy only a small part of the heap. There are three
generations of objects on the heap:
Newly allocated objects form a new generation of objects and are implicitly
generation 0 collections, unless they are large objects, in which case they go on the
large object heap in a generation 2 collection.
Most objects are reclaimed for garbage collection in generation 0 and do not survive
to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer
between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-
lived object is an object in a server application that contains static data that is live
for the duration of the process.
2 {
4 {
5 testid = "";
6 return;
7 }
9 throw;
10 }
In C#6.0,
2{
3 testid = "";
4 return;
5}
2 Red,
3 Blue,
4 Black,
5 White
6 }
1 // File1.cs
2 using System;
3 namespace Outer.Inner
4 {
5 class Foo
6 {
8 {
9 double d = Math.PI;
10 }
11 }
12 }
13
14 // File2.cs
15 namespace Outer
16 {
17 class Math
18 {
19 }
20 }
The compiler searches Outer before looking at those using statements outside the
namespace, so it finds Outer.Math instead of System.Math. Outer.Math has no PI
member, so File1 is now broken.
This changes if you put the “using” inside your namespace declaration, as follows:
1 // File1b.cs
2 namespace Outer.Inner
3 {
4 using System;
5 class Foo
6 {
8 {
9 double d = Math.PI;
10 }
11 }
12 }
Now the compiler searches ‘System’ before searching ‘Outer’, finds ‘System.Math’.
So this will work fine.
5. Should a return statement be inside or outside a
lock statement?
Whether you put the return statement inside or outside a lock statement, It doesn’t
make any difference; they’re both translated to the same thing by the compiler.
1 void example() {
2 int testData;
3 lock (foo) {
4 testData = ...;
5 }
6 return testData
7}
vs.
1 void example() {
2 lock (foo) {
3 return ...;
4 }
5}
It is recommended to put the return inside the lock. Otherwise you risk another
thread entering the lock and modifying your variable before the return statement,
therefore making the original caller receive a different value than expected.
2{
4}
If you are trying to use a generic Dictionary in C# like you would use an associative
array in another language:
2{
3 foo(item.Key);
4 bar(item.Value);
5}
Or, if you only need to iterate over the collection of keys, use
2{
3 foo(item);
4}
2{
3 foo(item);
4}
So Microsoft has faciliated the Idisposable Interface and Dispose method to clean up
unmanaged resources.
2 using System.IO;
4 {
6 public UnmangedWrapper()
7 {
9 }
10 ~UnmangedWrapper()
11 {
12 Dispose(false);
13 }
15 {
16 Dispose();
17 }
19 {
20 Dispose(true);
21 System.GC.SuppressFinalize(this);
22 }
24 {
25 if (disposing)
26 {
27 if (Stream != null)
28 {
29 Stream.Close();
30 }
31 }
32 }
33 }
1 class Person
2 {
3 public Person()
4 {
11 }
13 }
1 //Example:
3 int n = r.Next();
When using Regular Expressions you should use the following namespace:
1 using System.Text.RegularExpressions;
5 MessageBox.Show(result[i]);
7 //Output:
8 test1
9 test2
10 test3
11 test4
1 ConfigurationManager.AppSettings["MySetting"]
2 {
6 return Utility<T>.Create();
7 }
8 }
12 {
13 static Utility()
14 {
15 Create =
16 Expression.Lambda<Func<T>>(Expression.New(typeof(T).GetConstructor(Type.EmptyTypes))).Compile();
17 }
The connection pool implementation does not have a maximum size parameter – it
will keep creating new connections to meet demand (eventually it will hit some
system limit and the request will fail in some way that isn’t specified.
– By Using Partial Classes, multiple developer can work on the same class easily.
– Partial classes are mainly used by code generator to keep different concerns
separate
– you can also define Partial methods as well where a developer can simply define
the method and the other developer can implement that.
– An async method must have the async keyword in its method header, and it must
be before the return type.
– This modifier doesn’t do anything more than signal that the method contains one or
more await expressions.
– It contains one or more await expressions. These expressions represent tasks that
can be done asynchronously.
– It must have one of the following three return types.
− void :If the calling method just wants the async method to execute, but doesn’t
need any further interaction with it
− Task : If the calling method doesn’t need a return value from the async method,
but needs to be able to check on the async method’s state
− Task :If the calling method is to receive a value of type T back from the call, the
return type of the async method must be Task
– An async method can have any number of formal parameters of any types but it
cannot be out or ref parameters.
– The name of an async method should end with the suffix Async.
– Otherthan Methods, lambda expressions and anonymous methods can also act as
async objects.
What is the use of private constructor in C#?
A private constructor is a special instance constructor. It is generally used in classes
that contain static members only. If a class has one or more private constructors and
no public constructors, other classes (except nested classes) cannot create instances
of this class.
2 {
3 private Counter() { }
6 {
7 return ++currentCount;
8 }
9 }
10
11 class TestCounter
12 {
14 {
18
19 Counter.currentCount = 10;
20 Counter.IncrementCount();
22
26 }
27 }
1 //Example1
2 using System;
4 {
5 static Student()
6 {
8 }
10 }
11 // Example2
12 using System;
14 {
16 static MyStaticClass()
17 {
18 count = 0;
22 {
24 }
25 }
28
29 Output:
2 : this( a, b )
3 {
4 this.m_C = c;
5 }
7 : this( a, b )
8 {
9 this.m_D = d;
10 }
12 {
13 this.m_A = a;
14 this.m_B = b;
15 }
1 class Employee
2 {
3 // Copy constructor.
5 {
6 Name = previousEmployee.Name;
7 Age = previousEmployee.Age;
8 }
12 // : this(previousEmployee.Name, previousEmployee.Age)
13 //{
14 //}
15
16 // Instance constructor.
18 {
19 Name = name;
20 Age = age;
21 }
22
24
26
28 {
30 }
31 }
32
33 class TestEmployee
34 {
36 {
39
42
44 Employee1.Age = 39;
45 Employee2.Age = 41;
46
48 Employee2.Name = "Charles";
49
50 // Show details to verify that the name and age fields are distinct.
51 Console.WriteLine(Employee1.Details());
52 Console.WriteLine(Employee2.Details());
53
56 Console.ReadKey();
57 }
58 }
59 // Output:
60 // George is 39
61 // Charles is 41
1 Class Student
2 {
3 int roll;
4 float marks;
6 {
7 roll = a;
8 marks = b;
9 }
10 //other members
11 }
The above defined constructor takes two arguments one int and other float to
initialize instance members roll and marks for the newly created object and
therefore it is called parameterized constructor. With this type of constructor, the
object will be created as follows :
1 using System;
3 {
4 public OverloadStudent ()
5 {
6 //Default constructor
7 }
9 {
11 }
13 {
15 }
16 }
Now, following are the ways through which we can instantiate the object.
3{
4 this.x = x;
5 this.y = y;
6}
2 myClass b = (myClass)a.Clone();
Can we Overload main() method in C#?
Yes, We can overload main() method. A C# class can have any number of main()
methods.
But to run the C# class, class should have main() method with signature as “public
static void main(String[] args)”. If you do any modification to this signature,
compilation will be successful. But, You will get run time error as main method not
found.
2 {
4 {
7 }
9 {
11 }
12
14 {
16
17 return d;
18 }
19 }
2 {
4 {
7 }
9 }
2 {
4 {
7 }
9 }
2 {
4 {
5 return 100;
6 }
8 }
2 {
4 {
6 }
8 }
There can only be one entry point in a C# program. If you have more than one class
that has a Main method, you must compile your program with the /main compiler
option to specify which Main method to use as the entry point.
1. What is Dynamic Language Runtime?
o DLR is a runtime environment that adds a set of services for dynamic
languages to the CLR
o DLR makes it easier to develop dynamic languages to run on .net framework
and give them .net interoperability
o DLR introduces dynamic objects in C#
o DLR helps you create libraries that support dynamic operations
o Examples of languages developed by using DLR is IronPython,IronRuby etc
Advantages:
o The ability to use a rapid feedback loop (Read-Evaluate-Print loop). This lets
you enter several statements and immediately execute them to see the
results
o Supports both top-down and buttom-up development
o When you use top-down approach, you can call functions that are not yet
implemented and add underlying implementation when you need them
o Easier refactoring and code modification
The DLR adds a set of services to the CLR for better supporting dynamic languages.
These services include the following:
o Expression trees:
o The DLR uses expression trees to represent language semantics. For this
purpose, the DLR has extended LINQ expression trees to include control
flow, assignment, and other language-modeling nodes.
o Call site caching:
o A dynamic call site is a place in the code where you perform an
operation like a + b or a.b() on dynamic objects. The DLR caches the
characteristics of a and b (usually the types of these objects) and
information about the operation. If such an operation has been
performed previously, the DLR retrieves all the necessary information
from the cache for fast dispatch.
o Dynamic object interoperability
o The DLR provides a set of classes and interfaces that represent dynamic
objects and operations and can be used by language implementers and
authors of dynamic libraries. These classes and interfaces
include IDynamicMetaObjectProvider, DynamicMetaObject, DynamicOb
ject, and ExpandoObject.
The DLR uses binders in call sites to communicate not only with the .NET
Framework, but with other infrastructures and services, including Silverlight and
COM. Binders encapsulate a language’s semantics and specify how to perform
operations in a call site by using expression trees. This enables dynamic and
statically.
5.What are the Binders and What all are the binders
supported by .net framework?
The DLR uses binders in call sites to communicate not only with the .NET
Framework, but with other infrastructures and services, including Silverlight and
COM. Binders encapsulate a language’s semantics and specify how to perform
operations in a call site by using expression trees. This enables dynamic and
statically.
Object means a real word entity such as pen,paper, chair, table etc.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
2. What is a class?
A class can be defined as the primary building block of OOP. A class contains data
and behavior of an entity.
1. data member
2. properties
3. constructor
4. methods
Notes:
1. Class name should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.
2. The name of the constructor is always same as the class name
3. A class can have any number of data members, properties, constructors and
methods
4. Data member defined using a class is called as object reference.
5. A class can have a data member which is an object reference of the same class
Like the manager of the employee is also a employee.
3. What is an Object?
An entity that has state and behavior is known as an object e.g. pen, table, car etc.
It can be physical or logical.
For Example: Pen is an object. Its name is Parker, color is black etc. known as its
state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects
are created. So object is the instance(result) of a class. For example, you have a
class called Vehicle and car is the object of that class.
o Single Inheritance : contains one base class and one derived class
o Hierarchical Inheritance : Contains one base class and multiple derived
classes of same base class
o Multilevel Inheritance : Contains a class derived from a derived class
o Multiple Inheritance : Contains several base class and a derived class
9. What is Constructor?
C# constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
A constructor is a special method that is used to initialize an object. Every class has
a constructor,if we don’t explicitly declare a constructor for any C# class the
compiler builds a default constructor for that class. A constructor does not have any
return type. Constructors are responsible for object initialization and memory
allocation of its class.
A Destructor is used to free the dynamic allocated memory and release the
resources. You can Implement a custom method that allows to control object
destruction by calling the destructor.
o Public
o Private
o Protected
o Internal
o Protected internal
Example:
2 {
3 public int addition(int a, int b) //Two int parameters with same method
4 {
5 return a + b;
6 }
7 public int addition(int a, int b,int c) //Three int Parameters with same method
8 {
9 return a + b + c;
10 }
11 public float addition(float a, float b,float c,float d) //four float type Parameters with same method same as above two
method
12
{
13
return a + b + c + d;
14
}
15
Example:
2 {
4 {
5 return 10;
6 }
7 }
8 public class Amount:test
9 {
11 {
12 return 500;
13 }
14 }
The signature of delegates matches the signature of the function that it points to
else you will get compilation error.
Delegates are typesafe pointers because it points to a function and holds the
signature of the function.
Array Collection
of its declaration.It can not be resized. as per users requirement.It does not have fixed size
1.You can shadow a base class member in the derived class by using the keyword
New.
2.The method signature, access level and return type of the shadowed member can
be completely different than the base class member.
3.A method or function of the base class is available to the child (derived) class
without the use of the “overriding” keyword.
4.The compiler hides the function or method of the base class. This concept is
known as shadowing or method hiding.
5.In the shadowing or method hiding, the child (derived) class has its own function,
the same function is also available in the base class.
Overriding:
Class Structure
By default, the members of a Class are private By default, the members of a Structure are public
Nested classes has the ability to specify private as an access modifier for the class
itself.The use of the private access modifier defines the intended accessibility of the
class and prevents access from outside the class.
Static Polymrphism:
The mechanism of linking a function with an object during compile time is called
early binding. It is also called static binding. C# provides two techniques to
implement static polymorphism. They are:
1.Function overloading
2.Operator overloading
Dynamic Polymorphism:
The mechanism of linking method to an object during run time is called late
binding.It is also known as run-time polymorphism. Method overriding helps to
implement Dynamic Polymorphism.
ASP.NET
o Now just run the application to see WebForm1.aspx page and view its source
code. HTML source of the page will display form element as follows:
<code>form id="form1" action="WebForm1.aspx"
method="post">
o You can see that an HTML form element generated with an HTTP method as
“POST” and action=”WebForm1.aspx”. So, if a submit button is clicked, the
page will postback to itself by default.
o Following figure will also give you more understanding on ASP.NET Postback.
LoadPostBackData: is also a post back stage and loads the data posted for the
controls and update them.
Load: In this stage page as well as all the controls raise their Load event. Till this
stage all the controls are initialized and loaded. In most of the cases, we are coding
this event handler.
RaisePostBackEvent: is again a postback stage. For example, it’s raise against a
button click event. We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.
You can see the detailed explanation on ASP.net page life cycle here
There is a good list of events that are fired but following are few of the important
events in Global.asax:
You can read the difference between view state,session state and Application
state here.
o In-Process is the default approach. It stores session state locally on same web
server memory where the application is running.
o StateServer mode stores session state in a process other than the one where
application is running. Naturally, it has added advantages that session state is
accessible from multiple web servers in a Web Farm and also session state
will remain preserved even web application is restarted.
o SQLServer mode stores session state in SQL Server database. It has the same
advantages as that of StateServer.
o Custom modes allows to define our custom storage provider.
o Off mode disables session storage.
13.Globalization Vs Localization
When we need to build an application that work for multiple cultures e.g en-US, ar-
SAetc, this process of designing and building applications that work for more than
one cultures is called globalization. However, customizing an application for a
specific culture is localization. Both globalization and localization normally go
together.
14. How to access information about a user’s locale in
ASP.NET?
User’s locale information can be accessed
through System.Web.UI.Page.Culture property.
while UICulture is specific in localizing visual part of a webpage like Language being
used to display the contents of the web page.
Session.Clear() clears all the session values but doesn’t destroy the Session.
In otherwords ,Session.Clear() is like deleting all files inside a folder (say “Root”) but
Session.Abandon() means deleting the “Root” folder.
Local resources are specific to web page and stored in a folder App_LocalResources.
It can be accessible to that specific page only. Global resources are accessed by
almost all application pages and stored in App_GlobalResources folder.
Serving application data even if the original source is temporarily down, thus
improving availability of an application.
1. What is Caching and what are the pros and cons of
using it?
Caching is a mechanism that improve performance for an application by storing data
in memory for fast access.
When the application will access data from Cache (i.e. in-memory) instead of
fetching it from original data store (may be a database), it will definitely improve
performance.
But Caching benefits are not limited to performance only, it also improve application
Scalability as well as Availability.
o Load on server is reduced when data is fetched from Cache instead of original
source, thus improving scalability of an application.
o Caching normally keep serving application data even if the original source is
temporarily down, thus improving availability of an application.
Advantages:
Disadvantages:
In case of Page Output Cache, the output of a complete web page is stored in a
cache.
So, when that web page is accessed again, it will be loaded from cache instead of
fetching page data again from data source.
For Partial Page Cache (also known as Page Fragment Cache), a part or fragment of a
web page is stored in Cache as opposed to complete page caching for Page Output
Cache.
For example, caching a user control on a web page that displays product categories
using Page Fragment Cache.
Data Cache
In some scenarios, we may store frequently used objects into cache using ASP.NET
Cache API.
So, later on, that object will be loaded from cache instead of instantiating object
again and fetching data from original source for it.
4. Authentication Vs Authorization?
Authentication and Authorization are two key security related concepts that are
independent but normally go together.
For example, when a user tries to login a web application. First of all, user identity
is verified that either he/she is valid registered user of application.
If his/her identity validated successfully then appropriate privileges are assigned
accordingly.
Different users may have different privileges on same application, for example,
user1 can only view/read some records while user2 may have privileges for all CRUD
(Create, Read, Update, Delete) operations on same data.
2
Cache.Add(“ProductKey”,
3
objProduct,
4
null,
5
DateTime.Now.AddSeconds(60),
6
Cache.NoSlidingExpiration,
7
CacheItemPriority.High,
8
null);
To retrieve it back:
Passport benefits users because they do not need to log on to new limited-access
resources or sites
1. The sign-in, sign-out, and registration pages are centrally hosted rather than
being specific to each individual site.
2. All .NET Passport sign-in and core profile cookies are strongly encrypted.
3. The central .NET Passport servers return encrypted sign-in and profile
information to your site.
4. Members do not need to retype their sign-in name and password when moving
from site to site.
5. Participating Web sites never receive a member’s password. The
authentication cookie is actually a pair of encrypted time stamps asserting
when the member signed in.
6. There is no real-time, server-to-server communication between participating
Web sites and the central .NET Passport servers.
7. All information exchange occurs through the client’s browser using HTTP
redirects, encrypted information on the query string, and cookies.
<authorization >
<allow roles=”MyDomain1Administrators” / > < !– Allow Admin of this domain —
>
<deny users=”*” / > < !– Deny anyone else. — >
</authorization >
Login Control:
In almost every application we need to take user credentials on a typical login page.
Login control provides the same standard functionality and reduces the effort for
building it from scratch.
LoginName:
After a user successfully logged in to an application, we normally display his/her
username to top right or some other place on the page. Now, this functionality is
provided by LoginName control.
LoginView Control:
LoginView control displays different view for different users. Using
AnonymousTemplate and LoggedInTemplate, different information can be presented
to different users.
LoginStatus Control:
LoginStatus control implies whether a user is authenticated or not. For an
unathenticated user, it displays a link to login page. On the other hand, for
authenticated user, a logout link is displayed.
LoginRecovery Control:
Password recovery is another important functionality simplified through
PasswordRecovery control. It sends an email with login credentials to registered user
email.
It’s .NET CLR’s security system that restrict the code to perform an unwanted task
by applying security policies. Using CAS (Code Access Security), we can restrict what
our code can do? and also what code can call our code?
o Defines permissions and permission sets that represent the right to access
various system resources.
o Enables code to demand that its callers have specific permissions.
o Enables code to demand that its callers possess a digital signature, thus
allowing only callers from a particular organization or site to call the
protected code.
o Enforces restrictions on code at run time by comparing the granted
permissions of every caller on the call stack to the permissions that callers
must have.
o caspol -security on
o caspol -security off
We can also list all code groups using following command.
o caspol -listgroups
<configuration>
<system.web>
<identity impersonate=”true”/> <! — To disable set impersonate=”false” –>
</system.web>
</configuration>
o Creational Patterns
o This type of pattern address problems of creating an object and
separating it from operations
o Structural Patterns
o This type of pattern address problems of using object oriented constructs
to organize classes and objects
o Behavioral Patterns
o This type of pattern address problems of assigning responsibilities to
classes
4.What is Creational Design Pattern?
In software engineering, creational design patterns are design patterns that deal
with object creation mechanisms, trying to create objects in a manner suitable to
the situation.
o Singleton
o Factory
o Abstract Factory
o Prototype
o Builder
Structural Design Patterns are Design Patterns that ease the design by identifying a
simple way to realize relationships between entities.
o Adapter
o Bridge
o Composite
o Decorator
o Facade
o Flyweight
o Proxy
o Define an Interface for creating an object but let subclasses decide which
class to instantiate
o Lets a class defer instantiation to subclasses
You can see more details on Abstract Factory Design patterns here.
You can see more details on Builder Factory Design patterns here.
o Facade Design Pattern makes a software library easier to use, understand and
test
o Facade Design Pattern make the library more readable
o Facade Design Pattern reduce dependencies of outside code on the inner
workings of a library
o Facade Design Pattern wrap a poorly designed collection of APIs with a single
well-designed API.
o Proxy Design pattern involves a class, called proxy class, which represents
functionality of another class.
o Proxy is a wrapper or agent object that is being called by the client to access
the real serving object behind the scenes.
MVC
By using MVC pattern, we can develop applications that are more flexible to changes
without affecting the other components of our application.
It maps request URL to a specific controller action using a Routing Table.In order to
describe user’s actions, MVC framework uses friendly URLs against actions instead of
mapping it to physical files as in case of an asp.net Web Form application.
o Action filters are used when you want to apply some specific logic before or
after action methods.
o You can apply these action filters to a controller or a specific controller
action.
o Action filters are basically custom classes that provide a mean for adding pre-
action or post-action behavior to controller actions.
You can read the more detailed article on Action filter here.
Now ASP.NET MVC relieves the pain in attaining the role based security just by a simple
powerful attribute known as Authorize.
In default all the Controllers and Action methods are accessible by both Anonymous
andAuthenticated users.
All the public methods inside the Controllers can be easily accessed if one knows the method
name and the route pattern.
You can read the detailed article on Authorize attribute and its significance here.
Advantages:
This platform provides the major security like Two Factor Authentication, Account
Lockout, and Account Confirmation etc
You can read the more detailed information on ASP.net Identity here.
HTML helper are comparatively lightweight because they don’t have view state and
event model like Web Form Controls.
Along with the built in HTML helpers, we can also create our own custom helpers to
fulfill our specific needs.
o URL Helpers
o HTML Links
o Image Links
o HTML Form Elements
Advantages:
using Partial View in ASP.NET MVC has following advantages:
Multiple View Engines are available for MVC including ASPX, Razor, NHaml etc.
Normally in ASP.NET MVC, a View Engine translates view into HTML by:
ASPX View Engine is also known as Web Form View Engine. it’s syntax as “<%= %>” or
“<%: %>” for rendering server-side contents.
o Bеttеr execution
o Lоwеr аѕѕеt utilizаtiоn
o An аѕуnс mоdеl for еnhаnсеd еxесutiоn
o Adaptability
o Eсоnоmу in cloud-based fасilitаting ѕituаtiоnѕ.
HTML5
o MP3
o Wav
o Ogg.
Syntax:
<audio controls>
<source src=”testAudio.mp3″ type=”audio/mpeg”>
Your browser does’nt support audio embedding feature.
</audio>
Description:
src value can be relative as well as absolute URL. We can also use
multiple <source> elements pointing to different audio files.
o MP4
o WebM
o Ogg
Syntax:
<video> tag has associated optional attributes as controls, autoplay, preload, loop,
poster, width, height and other global attributes etc. Controls, loop, preload and
autoplay are already explained above. Others are explained below:
o poster – it’s basically a URL of the image that needs to display until video get
started.
o width – video player width
o height – video player’s height
<source> Tag: <source> is helpful for multiple media sources for audio and video.
There are two different objects which can be used to store data.
o localStorage object stores data for a longer period of time even if the
browser is closed.
o sessionStorage object stores data for a specific session.
SessionStorage LocalStorage
visible only to respective window or tab. and tabs from same origin.
Maximum size for localStorage is more between
o frame
o frameset
o noframe
o applet
o big
o center
o basefront
o Media API
o Text Track API
o Application Cache API
o User Interaction
o Data Transfer API
o Command API
o Constraint Validation API
o History API
<!doctype html>
<html manifest=”example.appcache”>
…..
</html>
navigator.geolocation.getCurrentPosition(show_map);
12.What are HTML5 Semantic Elements? Explain with
Example.
Semantic elements are those elements that clearly explains the purpose or meaning
of the element to user
(developer). For example, <div> and <span> elements in HTML doesn’t explain what
they will contain as contents. On the other hand, <img> and <form> elements clearly
explains the contents it can contain.
o <header>
o <nav>
o <aside>
o <section>
o <article>
o <footer>
o <details>
o <figure>
o <figcaption>
o <main>
o <mark>
o <nav>
o <summary>
o <time>
On the other hand, <section> tag refers to specific section of a document or page for
grouping purpose. For Example, at the end of this page, we have a specific section
for related list of “Top Interview Questions And Answers Series”. Or in right nav, we
have a section for “Top Posts and Pages” of this website.
<article>
<h1>Interview Questions Series</h1>
<p>List of Interview Questions on Java>
<section>
<h1>HTML5 Interview Questions</h1>
<p>List of Interview Questions on HTML5</p>
</section>
<section>
<h1>JavaScript Interview Questions</p>
<p>List of Interview Questions on JavaScript</p>
</section>
<section>
<h1>ASP.NET MVC Interview Questions</p>
<p>List of Interview Questions on ASP.NET MVC</p>
</section>
</article>
HTML5 web worker normally exists in external files and used for long-running CPU
intensive tasks but without affecting the User Interface or other scripts.
Limitations:
Few JavaScript objects are not accessible to HTML5 web worker as:
o parent object
o window object
o document object
15.Canvas Vs SVG?
Canvas SVG
o New multimedia elements that supports for embedding audio, video and
much more.
o Support for interactive graphics.
o New Form elements introduced in HTML5 including datalist, datetime,
output, keygen, date, month, week, time, number, range, email, url etc.
o Elements deprecated in HTML5 are frame, frameset, noframe, applet, big,
center etc.
o New APIs (Media API, Text Track API, Application Cache, User Interaction,
Data Transfer API, Command API etc.) provided.
o HTML5 supports on different plateform like PC, TV , Mobile devices etc.
o Supporting web applications for offline data storage.
o more lightweight as compared to other image formats like jpeg and gif etc.
o XML-based
o support for animation
o maintain better quality even if re-sized
o faster rendering
o Chrome 4
o IE 8+
o firefox 3.5+
o Safari 4
o Opera 10.5