We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Sunday, August 2, 2015

Generics And Collections in C#

1 What are Generics?
Ans:- Generic is Substitutable Data type which can be Substituted at runtime by any reference type or value type without committing to actual types 

2 What are the uses of Generics?

Generic allows you to create type-safe data structures without committing to actual types 
  
3 Why use Generics?
Generics code can be used with any Reference type or value type, Thus Generic Provide Code Reusability.

4 What are the Generic Type parameters?

Generic Type Parameter is a Placeholder for a Specific type that a client specifies when they try to Instantiate a Variable 

5 Is it Possible to Create Generic Field?

Yes. It is possible to create generic type and the default values of those types are null

6 What are the features of Generic?

Code Reusability, Type Safety, Faster Execution

7 What are the Benefits of Generic?

Provides Generalization to CLR

8 In which version of .Net Generic were introduced?

.NET Version 2.0

9 In the Earlier version of .Net what was the Mechanism used to achieve Generalization?

By Casting types from universal base type System.Object (Boxing and Un-Boxing)  

10 What are Generic Collections?

Generic Collections are Type safe Collections

11 Why are Generic Collections are brought into Picture?

Generic Collections were introduced to overcome the drawbacks of collections and arrays.

12 Which are Commonly used Generic Collection Classes?


  • List<T>
  • LinkedList<T>
  • Dictionary<Tkey,Tvalue>
  • SortedList<Tkey,Tvalue>
  • Stack<T>
  • Queue<T>

13 What are the Differences between Dictionary and SortedList?
Dictionary stored values in key value pair
SortedList is pretty much the same as Dictionary but SortedList values are sorted on Keys when inserted and it provides access the values through index

14 What are the Interfaces of Generic Collections?

ICollection, IDictionary, IComparable, IEnumerable, IEnumerator, IComparator

15 Is it Possible to Create a custom Collection?

Yes. It is possible to create our own custom Collections by implementing Collection Interfaces.

16 What is the namespace for Generic Collections?

System.Collections.Generic

17 Is it Possible to Create Generic Classes?

Yes. It is possible to create a generic class 
Syntax: class sample<T> {…}

18 Can Static class be Generic? 

No. Static Classes can’t be generic

19 Why Static Classes Can't Be Generic?
Because for static Classes, memory is allocated only once but in concept of generic memory is needed to allocate more than once at Run-Time. Thus Static class aren’t possible

20 Can Static Methods be Generic?

Yes. A static method can be generic

21 Can we define a Generic Extension Method?

Yes. We can Create a generic Extension method as Extension method are also static methods

22 Is it possible to Create a Generic Interface?

Yes.

23 What Happens When a Generic Method inside a Generic Class Have type parameters which are of the Same name?

C# Compiler will raise a warning CS0693 
Because the within the method scope the argument supplied for inner Type Parameter hides the value supplied for outer Parameter

24 Difference between C# Generics and C++ Templates?


  • C# will not all non-type parameters
  • C# will not allow Explicit Specialization of i.e, custom implementation of a template
  • C# will not allow Type parameters to have Default values  

25 How to assign Default values to Generic Keywords
By using the ‘default’ keyword

26 What are generic Constraints 

Generic Constraint is a mechanism to restrict the kind of types that client code can use.

27 What will happen when the client tries to instantiate a type which is not allowed by constraints?

It will end up in a Compile time error

28 Which key word is used to Specify Constraints?

‘where’ keyword is used to specify Constraints

29 What are the types of Constraints we can apply on generic type parameters


  • Structs – The type argument must be a value type
  • Classes – Type argument must a reference type
  • new() – Type argument must have a parameter less constructor
  • <Base Class name> -- Type arguments must be the child class of Defined base class
  • <interface name> -- Type argument must be a class that implements a defined interface

30 Can multiple Constraints be applied on a single Generic type Parameters
Yes. But Except Interfaces other Constraints should not be repeated

31 What is array covariance?
Arrays are covariant since C# 1.0. You can always do the following:
object[] obj = new String[10];
In the above code, I assigned an array of strings to an array of objects. So I used a more derived type than that originally specified, which is covariance. 
Covariance in arrays is considered “not safe,” because you can also do this:
obj[0] = 5;

32 What is the problem with nongeneric based collections in C#?



  •  All the nongeneric collection classes will perform Boxing, UnBoxing operations and Casting operations. Which may lead to exceptions.
  • Type safety is the main issue with non-generic collection classes or type safety is very less for non-generic collection classes.

33 How to create an object of a generic class?
A<int,float> a = new A<int,float>();
      While creating an object of a generic class you can pass any data type as a parameter to the class by specifying datatype in angular brackets.

34 What is an unbound type parameter in c# Generics?
A Type parameter without any restrictions.

35 What will happen if type generic Variable of the same type attempted to add?

The compiler will report an error: Operator '+' is not defined for types T and int.

36 The syntax for Providing multiple Constraints to Generic Type?

where T:class,<interface name>,new(){...}

37 Is it possible to perform Atrhematic operations With Generic? 

No. It is not possible.

38 what are the modifiers are allowed on a generic method?

Abstract, virtual, and override.

39 can generic classes can be nested?

Yes.

40 can application entry point be in the generic class declaration?

No

41 can we declare a virtual generic method?
Yes

42 Is it Possible to pass convert Implicitly pass commited types to a Generic method

Yes.

43 how can we use an alias for generic?

Using Y=namespacename.classname<int>;

44 what is the scope of type parameter on a class?

Class base,constraint clause,class body.

45.    What are Generic Delegates?

delegate can define its own type parameters. Code that references the generic delegate can specify the type argument to create a closed constructed type, just like when instantiating a generic class or calling a generic method, as shown in the following example:

public delegate void Del<T>(T item);
public static void Notify(int i) { }

Del<int> m1 = new Del<int> (Notify);

46 We have a code snippet like.....

public class MyContainer<T> where T: IComparable

{
// Insert code here
}
What is the need of that Incomparable in the above code?

Class MyContainer requires that it's type argument must implement IComparable interface.


47. Can we give multiple constriant on type argument? and if yes give example or if no then why?

Yes, we can give multiple constraints on the type argument.

Example:

public class MyContainer<T> where T: class, IComparable
{
//Insert code here
}

here Class MyContainer requires that its type argument must be a reference type and it must implement an IComparable interface.

48. Can we initailize a Generic List with some initial capacity and how?
Ans: Yes we can initialize List with some initial capacity by using the following constructor

List<T>(Int32)

49. What are the different types of collections?

 Collections are basically a group of records that can be treated as one logical unit.

.NET Collections are divided into four important categories as follows.
  • Indexed based.
  • Key-Value Pair.
  • Prioritized Collection.
  • Specialized Collection.
50. Explain about generics?
 Generics are not a completely new construct; similar concepts exist with other languages. Generics are defined with the CLR. This makes it possible to instantiate generics with a specific type in Visual Basic even though the generic class was defined with C#.

51. Why hashtables are not serialzable in .NET?
 The thing about XML Serialization is that it's not just about creating a stream of bytes. It's also about creating an XML Schema that this stream of bytes would validate against. There's no good way in XML Schema to represent a dictionary.

This limitation is not the only Hashtable, but the XmlSerializer also cannot process classes implementing the IDictionary interface due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

52. What is a List of Generic Type?

Lists are indexed based on Generic Collections. Lists are the Generic form of ArrayList.

For example,

List<int> ObjInt = new List<int>();

ObjInt.Add(123);

ObjInt.Add(100);

53. What is Dictionary<TKey, TValue>? 
 Dictionary is key-based generics collection. Dictionary is a generic form of Hashtable.

For example:

Dictionary<int, int> ObjDict = new Dictionary<int,int>();

ObjDict.Add(1,2);

Dictionary<int,string> ObjDict1 = new Dictionary<int,string>();

ObjDict1.Add(1,"mithilesh");

ObjDict1.Add(2,"Sonu");

ObjDict1.Add(3,"Kajal");

54. What is Stack<T>?
Stack generic collection allows you to get value in "LIFO"(last in first out) manner.

For example,

Stack<string> ObjStack = new Stack<string>();

ObjStack.Push("C#");

ObjStack.Push("ASP.NET");

ObjStack.Push("SQL SERVER");

Console.WriteLine(ObjStack.Pop());

55. What is collections Util?
It helps us to Create collections that ignore the case in String.

Example:

Hashtable ObjHash = CollectionsUtil.CreateCaseInsensitiveHashtable();

ObjHash.Add("Shyam","he is a good boy");

string str = (string) ObjHash["Shyam"];

MessageBox.Show(str);

56. Which values are not used in built in generic types?
Boolean, which is a nongeneric value type.

57. How does Generics enhance performance?
Because it is type-safe, due to which there is no need for Boxing and Un-Boxing.

58. What is the collection initializer?

 It's a new feature introduced in C#3.0 which gives us permission to initialize a collection at the time of declare.
Example:

List<int> liN = new List<int>(){ 1 , 4 , 5 , 7 };

59. Can we define a generic method with multiple types?
Yes. We can define eg.

Public void MyGenMethod<MyType>(MyType tp , int N)
{
Console.Write("{0} \n {1}",tp,N);
}

static void Main()
{
MyGeMethod<int>(10,20);
MyGeMethod<double>(10.20,30);
MyGeMethod<string>("Nacre",40);
}

60. Generics method or class can take any type as a type parameter, how can we restrict it to take only specific type?

Constraints can restrict a generic to take only specific type according to constriant imposed on Generic.
Example:
Class MyType<TP>where TP:struct
{
------
}
in this case, this class can take only value type as a type parameter.

61. What is Queue<T>?
Ans: Queue generic collection allows you to get value in "FIFO"(first in first out) manner.

For example,

Queue<int> ObjStr = new Queue<int>();

ObjStr.Enqueue(786);

ObjStr.Enqueue(123);

Console.WriteLine(ObjStr.Dequeue());

62. How can you delay the specifications of datatype?
Ans:: We Can Delay the Specifications Of DataType Using Generics

63. What are Constraints in Generics?
Ans Constraints are represented in C# using the where keyword

Constraints are something restriction the way doing that in generics

There are 3 types of Constraints

  • Constructor constraint
  • Derivation constraint
  • Reference / value type constraints
64. What are Generics and Casting? The C# compiler only lets you implicitly cast generic type parameters to Object, or to constraint-specified types

The compiler explicitly cast generic type parameters to only an interface but not a class.

65. How to use the IDispose of a Generic Type?

Just pass the value of generic type parameter to the using statement then the compiler will allow you to specify any instance of generic type

66. How to declare Generic Methods?
 The generic method is defined by specifying the type parameter after the method name but before the parameter list.

Example public string Add<T>(T val1, T val2).

67. What is the use of the Generic List?

  • Generic List is an efficient method of storing a collection of variables
  • Generic List is strongly typed and casting.
  • Name space to declare generics is using System.Collections.Generic.
68. Difference between Generics List and Array List?
  • Array List is not type-safe because it faces problems of boxing and UN boxing.
  • List generics are type-safe and do not require boxing and UN boxing situations.
  • In terms of performance of application List generics is better than the array list.
  • Array List can save different types of data types.
  • List generics we can save only specific data type.
  • Array List consumes lots of memory compare to list generics.
69. What are unbounded type parameters?
Type parameters that have no constraints, such as T in public class SampleClass<T>{}, are called unbounded type parameters. Unbounded type parameters

70. What are the rules of Unbounded type parameters?

 The != and == operators cannot be used because there is no guarantee that the concrete type argument will support these operators.

They can be converted to and from System.Object or explicitly converted to any interface type.
You can compare it to null. If an unbounded parameter is compared to null, the comparison will always return false if the type argument is a value type.

71.Difference between IEnumerator and IEnumerable?
IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this, in turn, allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement.


72. Does Generics shift the burden of type safety to the programmer rather than compiler?
 False
Lightweight dynamic methods can be Generic?

73. Does Generics provide type safety without the overhead of multiple implementations?

 True

74. Can We Use Generics delegates in C#.NET?
 Generics delegates are allowed in C#.NET.

75.Describe IList<T>
 It Represents a collection of objects that can be individually accessed by index.

76. What Are The Properties Of Icollections<T>?

There Are Two Properties Of Icollections<T>

  • ICount
  • IsReadOnly.
77. Only those procedures labeled as Generic are generic. Is It True or False?
False


78. How Information can be obtained on the types used in a generic data type at run-time?
Information on the types used in a generic data type can be obtained at run-time by means of reflection. 


79. What is the most common use of generics
The most common use of generics is to create collection classes.

                                                    



No comments: