Knowledge Conclusion - PART II : CSharp, .NET

/*****by Jiangong SUN*****/


Update 26/05/2013, 29/05/2013, 26/06/2013, 09/07/2013, 15/07/2013, 5/09/2013


PART II: .NET



1) What is interface ?
Answer:

An interface is like an abstract base class: any non-abstract type that implements the interface must implement all its members.

Knowledge Conclusion - PART II : CSharp, .NET_第1张图片

An interface cannot be instantiated directly.
Interfaces can contain events, indexers, methods, and properties.
Interfaces contain no implementation of methods.
Classes and structs can implement more than one interface.
An interface itself can inherit from multiple interfaces.

2) Which version of .NET framework do you have most experience. And what difference does it have with its precedent version ?

Answer:

.NET Framework 2.0 in 2002 with new features: Generics, anonymous method, nullable type

.NET Framework 3.0 in 2006 with new features: WCF, WPF, WF, CardService

.NET Framework 3.5 in 2007 with new features: ASP.NET AJAX, LINQ, Entity Eramework

.NET Framework 4.0 in 2010 with new features: Task Paralel library(TPL), BigInteger, Parallel LINQ,  Parallel Computing, dynamic keyword, Named arguments and Optional Arguments

.NET Framework 4.5 in 2012 with new features: .NET for Windows Store Apps, Portable Class Libraries, HTML5 support, asyn/await, integrated compression, regular expression timeout, garbage collector background cleanup


3) Difference between System.String and System.StringBuilder classes?
Answer:

System.String is immutable(unchangeable).  

System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. 

System.StringBuilder has better performance than string


4) .NET Root namespace, and top class, ASP.NET root class

The System namespace is the root of all namespaces in the .NET Framework, containing all other namespaces as subordinates.

The class System.Object is the root of the inheritance hierarchy in the .NET Framework. Every class in the .NET Framework ultimately derives from this class. If you define a class without specifying any other inheritance, Object is the implied base class.

reference: http://www.informit.com/articles/article.aspx?p=171028

ASP.NET root class System.Web.UI



5) What's the difference between IEnumerable<T> and List<T> ?
Answer:

IEnumerable is an interface, where as List is one specific implementation of IEnumerable. List is a class.


FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable, where as List can be iterated using several ways. 
List can also be indexed by an int index, element can be added to and removed from and have items inserted at a particular index.
IEnumerable doesn't allow random access, where as List does allow random access using integral index.
In general from a performance standpoint, iterating thru IEnumerable is much faster than iterating thru a List. 

6) What's the difference between EXE and DLL ?
Answer:
.EXE is an executable file and can run by itself as an application
.DLL is usullay consumed by a .EXE or by another .DLL and we cannot run or execute .DLL directly
In .NET framework, both .EXE and .DLL are called as assemblies.

7) What is a delegate?
Answer:
A delegate is a type safe function pointer. Using delegates you can pass methods as parameters. 
To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. 
This is why, delegates are called type safe function pointers.

The declaration of a delegate type is similar to a method signature.
A delegate can be instantiated by associating it either with a named or anonymous method.

C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code.


A simplified implementation of the Observer pattern
A simplified implementation of callbacks
Anonymous (non-reusable) blocks of code

8) What is the path of .net framework in windows system?
Answer: 
$System$\Windows\Microsoft.NET\Framework

9) What is the difference between value type and reference type?

Answer:

Difference:
When value-type instance is created, a single space in memory is allocated to store the value.
When reference-type instance is created, only the reference to the object is created.

Value type:

value type consist of 2 main categories: struct and enum

struct include: numeric types(integral type, floating-point types, decimal), bool, user defined structs.


integral type include: sbyte, byte, char, short, ushort, int, uint, long, ulong


floating-point types include: float and double.


enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong


Reference type:

String
All arrays
, even if their elements are value types
Class types, such as Form
Delegates

Elements not belong to types:
Namespaces
Modules
Events
Properties and procedures
Variables, constants, and fields


10) What is the difference between stack and heap ?
Answer:

The Stack is more or less responsible for keeping track of what's executing in our code.  
The Heap is more or less responsible for keeping track of our objects.

The Stack is self-maintaining, meaning that it basically takes care of its own memory management.  
When the top box is no longer used, it's thrown out.
The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to keep the Heap clean

Stack: value types, stack frames sequential (LIFO) scope pop deterministic
Heap: objects random reference count Garbage Collection nondeterministic

11) What is the difference between boxing and unboxing ?

Answer:

Boxing: convert from value type to reference type

Unboxing: contrary process 

Boxing is implicit; unboxing is explicit.

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;  // unboxing

12) What is extension methods ?
Answer: 
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. 
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable 
and System.Collections.Generic.IEnumerable(Of T) types.

To use the standard query operators, first bring them into scope with a using System.Linq directive. 
Then any type that implements IEnumerable(Of T) appears to have instance methods such as GroupBy, OrderBy, Average, and so on. 
You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable(Of T) type such as List(Of T) or Array. 

13) What is a final keyword in C#?
Answer:
Classes : To prevent subclassing (inheritance from the defined class):
Java:
public final class MyFinalClass {...}

C#:
public sealed class MyFinalClass {...}

Methods : Prevent overriding of a virtual method.
Java:
public class MyClass
{
    public final void myFinalMethod() {...}
}

C#:
public class MyClass
{
    public sealed void MyFinalMethod() {...}
}

Java by default marks all non-static methods as virtual, whereas C# marks them as sealed. 
Hence, you only need to use the sealed keyword in C# if you want to stop further overriding of a 
method that has been explicitly marked virtual in the base class.

Variables : To only allow a variable to be assigned once:
Java:
public final double pi = 3.14; // essentially a constant

C#:
public readonly double pi = 3.14; // essentially a constant

14) What is the difference between const and readonly ?
Answer:
'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

A const field can only be initialized at the declaration of the field. 
A readonly field can be initialized either at the declaration or in a constructor. 
Therefore, readonly fields can have different values depending on the constructor used. 
Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants.

15) What is virtual keyword ?
Answer:
virtual keyword is used to modify a method, property, indexer or event declaration and allow for it to be overridden in a derived class.
By default, methods are non-virtual.
You cannot override a non-virtual method.
You cannot use virutal modifier with static, abstract, private or override modifiers.

Fields cannot be virtual; only methods, properties, events and indexers can be virtual.

16) What is abstract ?

Answer:
The abstract modifier can be used with classes, methods, properties, indexers, and events.

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.
Abstract classes have the following features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Knowledge Conclusion - PART II : CSharp, .NET_第2张图片

Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
Abstract methods have the following features:
An abstract method is implicitly a virtual method.

Abstract method declarations are only permitted in abstract classes.


Because an abstract method declaration provides no actual implementation, there is no method body; 
the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. 
For example:
public abstract void MyMethod();
The implementation is provided by an overriding method, which is a member of a non-abstract class.
It is an error to use the static or virtual modifiers in an abstract method declaration.

17) What is override ?
Answer:
An override method provides a new implementation of a member that is inherited from a base class. 
The method that is overridden by an override declaration is known as the overridden base method. 
The overridden base method must have the same signature as the override method.

An override declaration cannot change the accessibility of the virtual method. 
Both the override method and the virtual method must have the same access level modifier.

You cannot use the new, static, or virtual modifiers to modify an override method.

18) What is main characteristics of object oriented programming ?
Answer:

Inheritance, Encapsulation, Polymorphism

19) What is inheritance ?

Answer:
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. 
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. 
A derived class can have only one direct base class. However, inheritance is transitive. 
If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

public class A
{
    public A() { }
}

public class B : A
{
    public B() { }
}


20) What is encapsulation ?
Answer:
The idea of encapsulation is that an object's internal data should not be directly accessible from an object instance.
In C#, encapsulation is enforced at the syntactic level using the public, private, internal, and protected keywords.

private   Only members within the same type. (default for type members)
protected Only derived types or members of the same type.
internal         Only code within the same namespace. An assembly can contain multiple namespaces. With internal keyword, the method or class can't be accessible by an another namespace in the same assembly. Can also be code external to object as long as it is in the same assembly. (default for types)
protected internal Either code from derived type or code in the same assembly. Combination of protected OR internal.
public   Any code. No inheritance, external type, or external assembly restrictions.


Accessor and Mutator:
private int profit;
public int SetProfit(int value)
{
profit = value
}
public int GetProfit()
{
returnn profit;
}

Property: (used in C# 2.0)
private int profit;
public int Profit
{
get{ return profit;}
set{ profit = value;}
}

Aumomatic property: (used in C# 3.0 and later)
public int Profit
{
get;
set;
}

21) What is polymorphism ?
Answer:
When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. 
To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, 
or you can override a virtual base member.

1. with new keyword:

public class BaseClass
{
    public void DoWork() { }
    public int WorkField;
    public int WorkProperty
    {
        get { return 0; }
    }
}

public class DerivedClass : BaseClass
{
    public new void DoWork() { }
    public new int WorkField;
    public new int WorkProperty
    {
        get { return 0; }
    }
}

Example:

Knowledge Conclusion - PART II : CSharp, .NET_第3张图片


2. with virtual and override keyword:

public class BaseClass
{
    public virtual void DoWork() { }
    public virtual int WorkProperty
    {
        get { return 0; }
    }
}
public class DerivedClass : BaseClass
{
    public override void DoWork() { }
    public override int WorkProperty
    {
        get { return 0; }
    }
}

22) What is the difference between ref and out ?

Answer:
The out and the ref parameters are used to return values in the same variables, that you pass an an argument of a method. 
These both parameters are very useful when your method needs to return more than one values.

The only difference is ref need to instaciate the variable before use it and out doesn't need to instanciate the variable before use it.

public static void Main()
{
int i, j; // variable need not be initialized
Console.WriteLine(TestOut(out i, out j));
Console.WriteLine(i);
Console.WriteLine(j);
}

public static int TestOut(out int iVal1, out int iVal2)
{
iVal1 = 10;
iVal2 = 20;
return 0;
}

public static void Main() 
{ 
int i; // variable need to be initialized 
i = 3; 
RefTest(ref i ); 
Console.WriteLine(i); 
}

public static void RefTest(ref int iVal1 ) 
{ 
iVal1 += 2; 
}

23) What is the difference between Accessor, Mutator et Property ?
Answer: 
Though we can encapsulate field data using traditional get and set methods, .NET prefers to enforce data protection using properties.
First of all, note that properties always map to accessor and mutator methods in terms of CIL (Common Intermediate Language) code. 
Thus, as a class designer, we're still able to perform any internal logic necessary before making the value assignment.

24) What is the difference between abstract method and virtual method ?
Answer:
An abstract function has no implemention and it can only be declared on an abstract class. 
This forces the derived class to provide an implementation. 


For example: 
public abstract int GetValue();

A virtual method is a method that can be overridden in a derived class using the override, replacing the behavior in the superclass. 
If you don't override, you get the original behavior. If you do, you always get the new behavior.


public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

25) Using keyword usage

Using reference: 

using Project = PC.MyCompany.Project;


Using Font or File:

using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

The reason why we use keyword "using" is that it disposes the resource correctly, without explicitly dispose the resource.

Why it needs to dispose the resources? Because it's not managed source, not managed code, so CLR can't use Garbage collector to collect the memory, you have to dispose it yourself.


26) ASP.NET MVC vs ASP.NET Web Forms

ASP.NET MVC is better for unit test, stateless, code clean

ASP.NET Web Forms is better for productivity


27) What is GAC?

GAC is Global Assembly Cache. The purpose is to share assembly for multiple applications.

Its location is < %windir%\Windows\assembly >.


28) How to chooose when to use abstract class or interface ?

Answer:

If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface.Abstract classes should be used primarily for objects that areclosely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Reference:

http://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx

http://visualstudiomagazine.com/articles/2010/06/22/whats-new-in-c-and-net-4.aspx


29) Serialization


Serialization is the process of converting an object into a stream of bytes in order tostore the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


30) What are different generations of programming language?

1st generation language: machine language

2nd generation language: assembly language

3rd generation language: high-level programming language,like C, CSharp, Java

4th generation language: mainly used in database, like SQL

5th generation language: mainly used in artificialintelligence and neutral networks, like prolog


你可能感兴趣的:(Knowledge Conclusion - PART II : CSharp, .NET)