Wednesday, June 29, 2011

C# Interview Questions & Answer 4

What are Properties in C#. Explain with an example?
Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.

The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.


using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;

// public FirstName property exposes _firstName variable
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}

}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}

Explain the 3 types of properties in C# with an example?
1. Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2. Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.

What are the advantages of properties in C#?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value of other fields.

What is a static property. Give an example?
A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.

using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

What is a virtual property. Give an example?
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.


using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is virtual
public virtual string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
}
class BankCustomer : Customer
{
// Overiding the FullName virtual property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}

What is an abstract property. Give an example?
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.


using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}

Can you use virtual, override or abstract keywords on an accessor of a static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.


Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"

Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No

Can you instantiate a struct without using a new operator in C#?Yes, you can instantiate a struct without using a new operator

Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.

Can a struct inherit from an interface in C#?Yes

Are structs value types or reference types?
Structs are value types.

What is the base type from which all structs inherit directly?All structs inherit directly from System.ValueType, which inherits from System.Object.

What are the 2 types of data types available in C#?
1.
Value Types
2. Reference Types

If you define a user defined data type by using the struct keyword, Is it a a value type or reference type?
Value Type

If you define a user defined data type by using the class keyword, Is it a a value type or reference type?
Reference type
Are Value types sealed?Yes, Value types are sealed.

What is the base class from which all value types are derived?
System.ValueType
Give examples for value types?Enum
Struct

Give examples for reference types?
Class
Delegate
Array
Interface
What are the differences between value types and reference types?
1.
Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.

Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);
The above code will compile, but at runtime System.NullReferenceException will be thrown.

How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;

What is the difference between System.Text.StringBuilder and System.String?
1.
Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.

How do you determine whether a String represents a numeric value?To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "One";
int i = 0;
if(int.TryParse(str,out i))
{
Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
Console.WriteLine("string does not contain Integer");
}

What is the difference between int.Parse and int.TryParse methods?
Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

Why should you override the ToString() method?
All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below.

using System;
public class MainClass
{
public static void Main()
{
int Number = 10;
Console.WriteLine(Number.ToString());
}
}

In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method.

If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class.

using System;
public class Customer
{
public string FirstName;
public string LastName;
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}

The code sample below shows how to override the ToString() method in a class, that would give the output you want.


using System;
public class Customer
{
public string FirstName;
public string LastName;

public override string ToString()
{
return LastName + ", " + FirstName;
}
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}

Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method.

C# Interview Questions & Answer 3

What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.

What are the 2 kinds of data type conversions in C#?
Implicit conversions:
No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.

What is the difference between an implicit conversion and an explicit conversion?
1. Explicit conversions require a cast operator where as an implicit converstion is done automatically.
2. Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.

What type of data type conversion happens when the compiler encounters the following code?ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();

Implicit Conversion. For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.

Will the following code compile?
double d = 9999.11;
int i = d;

No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.

double d = 9999.11;
int i = (int)d; //Cast double to int.

If you want to convert a base type to a derived type, what type of conversion do you use?Explicit conversion as shown below.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;

// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;

What operators can be used to cast from one reference type to another without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.

If casting fails what type of exception is thrown?InvalidCastException


What are the 3 types of comments in C#?
1. Single Line Comments. You define single line comments with // as shown below.
//This is an example for single line comment
2. Multi line comments. You define multi line comments with /* */ as shown below.
/*This is an example for
Multi Line comments*/
3. XML Comments. You define XML comments with /// as shown below.
///This is an example for defining XML comments.

Is C# a strongly-typed language?
Yes
What are the 2 broad classifications of data types available in C#?
1.
Built in data types.
2. User defined data types.
Give some examples for built in datatypes in C#?
1.
int
2. float
3. bool

How do you create user defined data types in C#?
You use the struct, class, interface, and enum constructs to create your own custom types. The .NET Framework class library itself is a collection of custom types provided by Microsoft that you can use in your own applications.

What are the 2 broad classifications of fields in C#?
1. Instance fields
2. Static fields

What are instance fields in C#?Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object.

What is a static field?
A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.

Will the following code compile?
using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}
No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields can only be accessed using the name of the class and not the instance of the class. The above sample program is rewritten as shown below.

using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}

Can you declare a field readonly?
Yes, a field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. An example is shown below.

using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}

Will the following code compile?

using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
A.PI = 3.15;
Console.WriteLine(A.PI);
}
}

No, PI is readonly. You can only read the value of PI in the Main() method. You cannot assign any value to PI.

What is wrong with the sample program below?

using System;
class Area
{
public const double PI = 3.14;
static Area()
{
Area.PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}
You cannot assign a value to the constant PI field.

What is the difference between a constant and a static readonly field?
A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.

What are the 4 pillars of any object oriented programming language?
1.
Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism

Do structs support inheritance?No, structs do not support inheritance, but they can implement interfaces.

What is the main advantage of using inheritance?
Code reuse

Is the following code legal?class ChildClass : ParentClassA, ParentClassB
{
}

No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.

What will be the output of the following code?
using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.

Does C# support multiple class inheritance?No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.

Explain polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];

DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();

foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}

When can a derived class override a base class member?
A derived class can override a base class member only if the base class member is declared as virtual or abstract.

What is the difference between a virtual method and an abstract method?
A virtual method must have a body where as an abstract method should not have a body.

Can fields inside a class be virtual?No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.

Give an example to show for hiding base class methods?
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}

Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}


C# Interview Questions & Answer 2

What is an abstract class?
An abstract class is an incomplete class and must be implemented in a derived class.

Can you create an instance of an abstract class?No, abstract classes are incomplete and you cannot create an instance of an abstract class.

What is a sealed class?
A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}

What are abstract methods?
Abstract methods are methods that only the declaration of the method and no implementation.

Will the following code compile?using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a compile time error stating "Customer.Test() cannot declare a body because it is marked abstract"

Is the following code legal?
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}

No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"

How can you force derived classes to provide new method implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}

public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}

public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation.
}
}

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

Can a sealed class be used as a base class?
No, sealed class cannot be used as a base class. A compile time error will be generated.

Will the following code compile?public abstract sealed class Test
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.


What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.

PrivateThe type or member can only be accessed by code in the same class or struct.

Protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

InternalThe type or member can be accessed by any code in the same assembly, but not from another assembly.

Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

What are Access Modifiers used for?Access Modifiers are used to control the accessibilty of types and members with in the types.

Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.

Can derived classes have greater accessibility than their base types?No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}


When you compile the above code an error will be generated stating "Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass".To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.


Is the following code legal?

using System;
private class Test
{
public static void Main()
{
}
}


No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"

Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support inheritance.

Can the accessibility of a type member be greater than the accessibility of its containing type?No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.

Can destructors have access modifiers?
No, destructors cannot have access modifiers.

What does protected internal access modifier mean?The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

What is the default access modifier for a class,struct and an interface declared directly with a namespace?
internal

Will the following code compile?
using System;
interface IExampleInterface
{
public void Save();
}

No, you cannot specify access modifer for an interface member. Interface members are always public.

What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing

Unboxing - Converting a reference type to a value typpe is called unboxing. An example is shown below.
obj = 101;
i = (int)obj; // Unboxing

Is boxing an implicit conversion?Yes, boxing happens implicitly.

Is unboxing an implicit conversion?
No, unboxing is an explicit conversion.

What happens during the process of boxing?Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.

What are constants in C#?
Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.

using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

Can you declare a class or a struct as constant?
No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Does C# support const methods, properties, or events?No, C# does not support const methods, properties, or events.

Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the example below, the constant field PI is always 3.14, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, PI), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference.

using System;
class Circle
{
public const double PI = 3.14;
}

How do you access a constant field declared in a class?
Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. In the example below constant field PI can be accessed in the Main method using the class name and not the instance of the class. Trying to access a constant field using a class instance will generate a compile time error.

using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}

C# Interview Questions & Answer 1

What is an array?
An array is a data structure that contains several variables of the same type.

What are the 3 different types of arrays?
1.
Single-Dimensional
2. Multidimensional
3. Jagged

What is Jagged Array?
A jagged array is an array of arrays.

Are arrays value types or reference types?Arrays are reference types.

What is the base class for Array types?
System.Array

Can you use foreach iteration on arrays in C#?Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#.


What do you mean by saying a "class is a reference type"?
A class is a reference type means when an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
What do you mean by saying a "struct is a value type"?A struct is a value type mean when a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.

When do you generally use a class over a struct?
A class is used to model more complex behavior, or data that is intended to be modified after a class object is created. A struct is best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
List the 5 different access modifiers in C#?
1.
public
2. protected
3. internal
4. protected internal
5. private
If you donot specify an access modifier for a method, what is the default access modifier?private

Classes and structs support inheritance. Is this statement true or false?
False, Only classes support inheritance. structs donot support inheritance.

If a class derives from another class, will the derived class automatically contain all the public, protected, and internal members of the base class?
Yes, the derived class will automatically contain all the public, protected, and internal members of the base class except its constructors and destructors.

Can you create an instance for an abstract class?
No, you cannot create an instance for an abstract class.
How do you prevent a class from being inherited by another class?Use the sealed keyword to prevent a class from being inherited by another class.

Classes and structs can be declared as static, Is this statement true or false?
False, only classes can be declared as static and not structs.
Can you create an instance of a static class?No, you cannot create an instance of a static class.

Can a static class contain non static members?
No, a static class can contain only static members.

What is the difference between string keyword and System.String class?
string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

Are string objects mutable or immutable?
String objects are immutable.
What do you mean by String objects are immutable?String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "First String ";
string s2 = "Second String";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;

System.Console.WriteLine(s1);
// Output: First String Second String

What will be the output of the following code?
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);
The output of the above code is "Hello" and not "Hello C#". This is bcos, if you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

What is a verbatim string literal and why do we use it?
The "@" symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:
string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";//Output: C:\Images\Buttons\SaveButton.jpg

string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/

string DoubleQuotesString = @"My Name is ""myname.""";
//Output: My Name is "myname."

Wednesday, June 22, 2011

Silverlight Overview


Silverlight
Microsoft Silverlight is a cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and rich interactive applications (RIA) for the Web. You can also create Silverlight applications that run outside of the browser on your desktop. Finally, you use the Silverlight framework to create applications for Windows Phone. Silverlight uses the Extensible Application Markup Language (XAML) to ease UI development (e.g. controls, animations, graphics, layout, etc.) while using managed code or dynamic languages for application logic.

What Is Silverlight?

Silverlight enables you to create a state-of-the-art application that has the following features:
  • It is a cross-browser, cross-platform technology. It runs in all popular Web browsers, including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari, Google Chrome, and on Microsoft Windows and Apple Mac OS X.
  • It is supported by a small download that installs in seconds.
  • It streams video and audio. It scales video quality to everything from mobile devices to desktop browsers to 720p HDTV video modes.
  • It includes compelling graphics that users can manipulate—drag, turn, and zoom—directly in the browser.
  • It reads data and updates the display, but it doesn't interrupt the user by refreshing the whole page.
  • The application can run in the Web browser or you can configure it so users can run it on their computer (out-of-browser). In addition, In addition, you can use your knowledge of the Silverlight framework to create Windows Phone applications.
Silverlight application with rich graphics and user interaction

Page turn screenshot
You can create Silverlight applications in a variety of ways. You can use Silverlight markup to create media and graphics, and manipulate them with dynamic languages and managed code. Silverlight also enables you to use professional-quality tools like Visual Studio for coding and Microsoft Expression Blend for layout and graphic design.

Silverlight combines multiple technologies into a single development platform that enables you to select the right tools and the right programming language for your needs. Silverlight offers the following features:
  • WPF and XAML. Silverlight includes a subset of the Windows Presentation Foundation (WPF) technology, which greatly extends the elements in the browser for creating UI. Silverlight lets you create immersive graphics, animation, media, and other rich client features, extending browser-based UI beyond what is available with HTML alone. XAML provides a declarative markup syntax for creating elements. For more information, see Layout, Input, and Printing, Graphics, Animation, and Media, and Controls.
  • Extensions to JavaScript. Silverlight provides extensions to the universal browser scripting language that provide control over the browser UI, including the ability to work with WPF elements. For more information, see JavaScript API for Silverlight.
  • Cross-browser, cross-platform support. Silverlight runs the same on all popular browsers (and on popular platforms). You can design and develop your application without having to worry about which browser or platform your users have. For more information, see Supported Operating Systems and Browsers.
  • Integration with existing applications. Silverlight integrates seamlessly with your existing JavaScript and ASP.NET AJAX code to complement functionality you have already created. For more information, see Integrating Silverlight with a Web Page.
  • Access to the .NET Framework programming model. You can create Silverlight applications using dynamic languages such as IronPython as well as languages such as C# and Visual Basic. For more information, see Managed API for Silverlight
  • Tools Support. You can use development tools, such as Visual Studio and Expression Blend, to quickly create Silverlight applications. For more information, see Silverlight Designer for Visual Studio 2010 and Expression Blend.
  • Networking support. Silverlight includes support for HTTP over TCP. You can connect to WCF, SOAP, or ASP.NET AJAX services and receive XML, JSON, or RSS data. For more information, see Networking and Web Services. In addition, you can build multicast clients with Silverlight. For more information, see Working with Multicast.
  • LINQ. Silverlight includes language-integrated query (LINQ), which enables you to program data access using intuitive native syntax and strongly typed objects in .NET Framework languages. For more information, see XML Data.
    Running Silverlight Applications


    To run a Silverlight web application, users require a small plug-in in their browser. The plug-in is free. If users do not already have the plug-in, they are automatically prompted to install it. The download and installation take seconds and require no interaction from the user except permission to install.
    Silverlight makes sure that you can run your applications in all modern browsers, without having to create browser-specific code. Silverlight applications can run in the browser or outside the browser

Fundamentals of Silverlight


Introduction to XAML

XAML stands for Extensible Application Markup Language. Its a simple language based on XML to create and initialize .NET objects with hierarchical relations. Altough it was originally invented for WPF, it's reused in Silverlight but it can by used to create any kinds of object trees.
Today XAML is used to create user interfaces in WPF and Silverlight, in WCF, to declare workflows in WF and for electronic paper in the XPS standard.
All types in Silverlight have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML.

Advantages of XAML

All you can do in XAML can also be done in code. XAML ist just another way to create and initialize objects. You can use Silverlight without using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your UI in XAML has some advantages:
  • XAML code is short and clear to read
  • Separation of designer code and logic
  • Graphical design tools like Expression Blend require XAML as source.
  • The separation of XAML and UI logic allows it to clearer separate the roles of designer and developer.

XAML vs. Code

As an example we build a simple StackPanel with a textblock and a button in XAML and compare it to the same code in C#.
<StackPanel>
    <TextBlock Margin="20">Welcome to the World of XAML</TextBlock>
<Button Margin="10" HorizontalAlignment="Right">OK</Button>
</StackPanel> 
The same expressed in C# will look like this:
// Create the StackPanel 
StackPanel stackPanel = new StackPanel();
this.Content = stackPanel;

// Create the TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(10);
textBlock.Text = "Welcome to the World of XAML";
stackPanel.Children.Add(textBlock);

// Create the Button
Button button = new Button();
button.Margin= new Thickness(20);
button.Content = "OK";
stackPanel.Children.Add(button);
As you can see is the XAML version much shorter and clearer to read. And that's the power of XAMLs expressiveness.

Properties as Elements

Properties are normally written inline as known from XML
 <Button.Content>
   <Image Source="Images/OK.png" Width="50" Height="50" />
</Button.Content>
</Button> 

Implicit Type conversion

A very powerful construct of Silverlight are implicit type converters. They do their work silently in the background. When you declare a BorderBrush, the word "Blue" is only a string. The implicit BrushConverter makes aSystem.Windows.Media.Brushes.Blue out of it. The same regards to the border thickness that is beeing converted implicit into a Thickness object. Silverlight includes a lot of type converters for built-in classes, but you can also write type converters for your own classses.
<Border BorderBrush="Blue" BorderThickness="0,10">
</Border>

Markup Extensions

Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup extensions are surrouded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}"). Silverlight has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension. These are the built-in markup extensions:
  • Binding To bind the values of two properties together.
  • StaticResource One time lookup of a resource entry
  • TemplateBinding To bind a property of a control template to a dependency property of the control
  • x:Static Resolve the value of a static property.
  • x:Null Return null
The first identifier within a pair of curly braces is the name of the extension. All preciding identifiers are named parameters in the form of Property=Value. The following example shows a label whose Content is bound to the Text of the textbox. When you type a text into the text box, the text property changes and the binding markup extension automatically updates the content of the label.
<TextBox x:Name="textBox"/>
<Label Content="{Binding Text, ElementName=textBox}"/> 

Namespaces

At the beginning of every XAML file you need to include two namespaces. The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all Silverlight controls in System.Windows.Controls. The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markupthat defines the XAML keywords. The mapping between an XML namespace and a CLR namespace is done by the XmlnsDefinition attribute at assembly level. You can also directly include a CLR namespace in XAML by using the clr-namespace: prefix.
<Window xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
</Window> 


Whats new in Silverlight 4.0 Beta 1

Introduction

Silverlight 4.0 is the next future version of Microsoft Silverlight. It will be released around summer 2010. Currently the first Beta version is available.

Tons of New Features

  • Broader Interaction capabilities
    • Printing support
    • Access to Microphone and WebCam
    • Audio and video recording
    • Copy and Paste or Drag and Drop from and to Silverlight applications
    • Mouse Wheel support for scrolling lists
    • Context Menu on Right-Click
    • Improved Multi-touch support with more gestures
  • API enhancements
    • HTML Control to embed web content. It can even be used as a brush.
    • Improved DataBinding capabilities (Grouping,Binding to DependencyObjects,StringFormatting)
    • New Controls (RichTextBox, MaskedTextBox, Enhanced DataGrid)
    • WCF RIA Services to bring your business data to Silverlight with a few clicks
    • Encanced Localization including Right-To-Left
  • Platform Enhancements
    • CLR compatibility between WPF and Silverlight
    • Performance optimizations (Applications run up to 200% faster)
    • Compatible with Google Chrome Browser
  • Media Enhancements
    • Multicast networking
    • Content protection for H.264 media
  • Trusted Applications
    • User Interface to request application privileges that exceed the silverlight sandbox
    • Read and write files to the user’s documents, music, pictures and videos folder
    • Run other desktop programs such as Office
    • Communicate with local devices by using COM automation
    • Full keyboard support in fullscreen mode
    • Cross-domain access without a security policy file
  • Development Environment Enhancements
    • Fully editable Silverlight designer in VS2010
    • Wire-up DataBinding by Drag&Drop

 

Create a simple Silverlight Application


Introduction

In this article I will show you how to create a simple silverlight application that shows a text, when the user clicks on a button. The result will look like this:


1. Ensure that you have the Tools installed

To get this sample running on your machine, you need Visual Studio 2008 and the Silverlight 3.0 Tools installed. You can get a detailed installation manual here.

2. Create a new Silverlight Project

Start Visual Studio 2008 and create a new "Silverlight Application Project" by choosing "File" -> "New" -> "Project...". Choose the destination path and give your project a meaningful name, then hit OK to create the project.
Silverlight solutions always consist of two projects. One that is the silverlight application itself - and one, that embeds it in a web page. Visual Studio asks you, if you want to embed your silverlight application in a simple HTML page, or in a full ASP.NET web application. For this example we choose "ASP.NET Web Application Project".
If we look at the files that Visual Studio created, we see the two projects "HelloSilverlightDemo" which is our silverlight application, and "HelloSilverlightDemo.Web" which is an ASP.NET web application that embeds our silverlight app into a webpage.
When we compile our solution, VisualStudio packs all XAML and DLLs into a deployment package that is called "HalloSilverlight.XAP. Its actually just a ZIP file that has been renamed. If you want to deploy your Silverlight to a web server, this file contains all information to make it run.

3. Place the controls

Unfortunately Visual Studio 2008 does not include a visual designer for Silverlight. If you want to use a visual designer, you can use Expression Blend to design your project. In our simple case we write directly the XAML code. Open the "MainPage.xaml" file and past the following code snipped to it:

<UserControl
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 x:Class="HelloSilverlightDemo.MainPage"
 Width="400" Height="100"gt;

<Grid Background="#FFECEDF0">
    <Button Margin="144,56,152,20" Content="Say Hello..." 
                Click="Button_Click" />
    <TextBlock x:Name="textBlock" Margin="80,16,88,60" 
                   FontSize="16" FontWeight="Bold" />
</Grid>
</UserControl>

The XAML code looks a bit like HTML. We use a Grid layout panel to align a Button and a TextBlock control on the surface. We define a margin, that defines the position of the elements. The Click="Button_Click" registers a callback function, that is called, when the button gets clicked.

4. Wire-up the interaction logic
Every UserControl in Silverlight consists of a view that defines the appearance and a code-behind file that defines the interaction logic. The view is defined in XAML and the code-behind is written in C# or VB.NET.
In the code-behind we have to define the callback-function "Button_Click", that is called when the button gets clicked. In this function, we set the text of the textBlock to "Hello Silverlight".
public partial class MainPage : UserControl
{
  public MainPage()
  {
      InitializeComponent();
  }

  private void Button_Click(object sender, RoutedEventArgs e)
  {
      textBlock.Text = "Hello Silverlight!";
  }
}

5. Test your application in the Browser

Now, we have done all our work, and we are curious, to see if it works. To test your application just hit [F5] and wait until Visual Studio has compiled all sources. A browser window will open automatically and load a webpage including your Silverlight app. To do this trick, VisualStudio brings up a small development web server. You can see its icon in the system tray. Now you can debug and test your application.