C Sharp - Generics

Generics

Generics are powerful – they allow you to develop the same method (or class) for different types of variables.

1
2
3
4
Public class adding <T>
{ public T Add(T a, T b)
{ return a+b; }
}

In this case we added a class named adding, which takes a variable type .

This is good, because since C# is hard typed, if you wanted to create an Add function, you might need to create one to add integers, another for floats, and another for long numbers. Instead you can use this one class.

Here is an example from class.

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
namespace EmployeeDirectory.Shared.Interfaces
{
public interface IResult<T>
{
bool WasSuccessful { get; set; }
T Model { get; set; }
string Message { get; set; }
}
}

namespace EmployeeDirectory.Shared.Common
{
public class Result<T> : IResult<T>
{
public bool WasSuccessful { get; set; }
public T Model { get; set; }
public string Message { get; set; }

public Result<T> ReturnError(string message = null)
{
WasSuccessful = false;
Message = message ?? "There was an error";
return this;
}
}
}

In this example we have created a Result object. It will be used to return result objects back from functions. The idea is rather than returning a ‘employee’ object. You’ll return a result object, which has an ‘employee’ object in its Model method.

A function using this interface would look like this

1
2
3
4
5
6
7
8
9
10
11
12
13
public IResult<List<EmployeeViewModel>> GetAllEmployess()
{
var list = new List<EmployeeViewModel>();
foreach (var employee in _context.Employees.ToList())
{
list.Add(employee.MapToEmployeeViewModel());
}
return new Result<List<EmployeeViewModel>>
{
WasSuccessful = true,
Model = list
};
}

The program calling the function will look like this

1
2
3
4
5
6
7
8
9
10
11
[HttpGet]
public IActionResult Get()
{
var result = _employeeService.GetAllEmployess();
if (result.WasSuccessful)
{
//return Ok(result.Model);
return Ok(result);
}
return BadRequest();
}