Thursday, January 22, 2015

Overview

Generics are amazing, here are some examples on how to use generics in C#. More info can be found here.

Examples

Properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Result<T> {
    public bool Success { get; set; }
    public T Data { get; set; }
}

public class AnotherResult<T, U> {
    public T Success { get; set; }
    public U Data { get; set; }
}

public class Program {
    public static void Main(string[] args) {
        var result = new Result<int> { Success=true, Data=5 };
        var result2 = new Result<string> { Success=false, Data="thingy" };
        var result3 = new AnotherResult<int, bool> { Success=5, Data=false };
        
        Console.WriteLine("Success: {0} - Data: {1}", result.Success, result.Data);
        // Success: true - Data: 5
        Console.WriteLine("Success: {0} - Data: {1}", result2.Success, result2.Data);
        // Success: false - Data: thingy
        Console.WriteLine("Success: {0} - Data: {1}", result3.Success, result3.Data);
        // Success: 5 - Data: false
    }
}

Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Result<T> {
    public bool Success { get; set; }
    public T Data { get; set; }
}

public class DoSomething {
    public void DoIt<T>(Result<T> result) {
        Console.WriteLine("Success: {0} - Data: {1}", result.Success, result.Data);
    }
}

public class Program {
    public static void Main(string[] args) {
        var result = new Result<int> { Success=true, Data=5 };
        var doSomething = new DoSomething();
        doSomething.DoIt(result);
        // Success: true - Data: 5
    }
}

Random Posts