Home > Net >  Doest non-generic members in different generic types are same or not
Doest non-generic members in different generic types are same or not

Time:05-03

public sealed class Reference<T>
{
    private static ulong maxID = 0;
    private ulong id = maxID  ;
    public ulong LongID => this.id;
    public Reference() { }
    public bool Equals(T? other)
        => other?.Reference.id == this.id;
    public bool Equals(Reference<T>? other)
        => other?.id == this.id;
    public override bool Equals(object? obj)
        => obj is T it ? Equals(it) : obj is Reference<T> rf ? Equals(rf) : false;
    public override int GetHashCode() => HashCode.Combine(this.id);

    public static bool operator ==(Reference<T>? left, Reference<T>? right)
        => left?.Equals(right) ?? false;

    public static bool operator !=(Reference<T>? left, Reference<T>? right)
        => !(left == right);

    public override string ToString() => $"Reference<{typeof(T).Name}> ({this.id})";
}

In this code i have class Reference<T> with static field. if i create new instance, hes got individual id
new Reference<T>(); id equals 0
new Reference<T>(); id equals 1
In dotnet when you use generic type under hood created new non-generic type
I think that Reference<T>.maxID has value 2 and Reference<T2>.maxID 0
But this fields non-generic, and it is quite possible that fields are sames in different generic types

CodePudding user response:

Yes, when you use generic type with new generic parameter(s) under the hood creates new non-generic type and all non-generic members also copy

new Reference<Int32>(); id are 0
new Reference<UInt32>(); id are 0, cause its different type

If i want to different result, i should create new non-generic class (not inside Reference<T>) with public|internal static field maxID and using him

CodePudding user response:

From C# 6 draft specification's section 8.4.3 Open and closed types:

Each closed constructed type has its own set of static variables, which are not shared with any other closed constructed types. Since an open type does not exist at run-time, there are no static variables associated with an open type. Two closed constructed types are the same type if they are constructed from the same unbound generic type, and their corresponding type arguments are the same type.

So for every different T in Reference<T>.maxID there will be different maxID.

In dotnet when you use generic type under hood created new non-generic type

Note that there is a small caveat here. Depending on the generic type parameters used (in particular if they are reference or value types) CLR implementation of C# can behave differently in terms of method compilation. To prevent generic code bloat for reference types methods code is reused while for every value type new implementation will be compiled. See .NET Generics and Code Bloat article.

  • Related