Yeo
Yeo

Reputation: 183

Understanding Generic Class implementation

I am trying to understand this code:

public interface IBuilding
{
    string Id { get; }
}

public class Model<TBuilding>
    where TBuilding : IBuilding
{
    public TBuilding Building { get; private set; }
}

What does Model<TBuilding> mean here? From my understanding, ClassName<T> stands for Generic Class. <T> can represent string, int etc. But <TBuilding> implements IBuilding interface here. Why does a generic type implement an interface? My suspicion is that <T> means <Id>. Am I correct?

I have no clue on how to understand this code. I read up on Generic Classes but could not find anything useful.

Upvotes: 0

Views: 104

Answers (3)

T.S.
T.S.

Reputation: 19340

This is a little misleading by naming

public interface IBuilding // interface contract
{
    string Id { get; }
    string ElevatorCount { get; }
}

// this is where you have confusion. T - is standard naming for generic type parameter
// if you start naming your generic type parameter TBuilding - 
// you will get confused that it might be some type
public class BuildingInspector<T>  where T : IBuilding // T : IBuilding - restricts types to IBuilding
{
    public BuildingInspector(T building) // generic type in constructor
    {
        Building = building;
    }

    public T Building { get; private set; }
    public int GetTotalElevatorCapacity(int kiloPerElevator)
    {
        return (this.Building.ElevatorCount * kiloPerElevator)  
    }
}

// U S A G E

public class SingleFamilyHome : IBuilding
{
    public string Id { get; private set; }
    public string ElevatorCount { get; private set; }
}
 . . . . .
private void TryUsingGenericType ()
{

    var famHome = new SingleFamilyHome(){ Id=1, ElevatorCount=0 };
    var famInspector = new BuildingInspector<SingleFamilyHome>(); // SUCCESS

    var capacity = famInspector.GetTotalElevatorCapacity(0);

    // this code will not compile because above you have --> where T : IBuilding
    var stringInspector = new BuildingInspector<string>(); // DESIGN TIME ERROR

}

Now that you see declaration AND usage, you can see how it is used. Best example is System.Collections.Generic.List<T>. You can have any list

List<string>
List<Building>
List<int>

Upvotes: 2

Iosif Bujor
Iosif Bujor

Reputation: 99

'Where' syntax is constraining your T type to be a type that implements IBuilding. Without the where condition, it would accept any types. Here you can find a more detailed explanation. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190945

Not exactly. T is just a placeholder for a type. If you have FireHouse, PoliceStation, Hospital, etc. implementing IBuilding you can provide one of those to Model and the Building property would only hold an instance of that type.

Upvotes: 4

Related Questions