Generics Intro

 

Scenario:

Per MSDN: Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T, you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operation.

Solution:

T is available to the nested class. GenericList<string> instantiated with a concrete type, T becomes string

    1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    public class GenricList<T>
        {
            private class Node
            {
                public Node(T t)
                {
                    next = null;
                    data = t;
                }
    
                private Node next;
    
                public Node Next
                {
                    get { return next; }
                    set { next = value; }
                }
    
                private T data;
    
                public T Data
                {
                    get { return data; }
                    set { data = value; }
                }
            }
    
            private Node head;
    
            public GenricList()
            {
                head = null;
            }
    
            public void AddHead(T t)
            {
                Node n = new Node(t);
                n.Next = head;
                head = n;
            }
    
            public IEnumerator<T> GetEnumerator()
            {
                Node current = head;
    
                while (current != null)
                {
                    yield return current.Data;
                    current = current.Next;
                }
            }
        }
          Calling GenericList
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class GenericsClass
        {
            static void Main(string[] args)
            {
                GenricList<int> list = new GenricList<int>();
                for (int i = 0; i < 5; i++)
                {
                    list.AddHead(i);
                }
    
                foreach (var l in list)
                {
                    Console.WriteLine($"{l} ");
                }
    
                Console.ReadLine();
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...