How to initialize generic parameter type T?

前端 未结 5 1960
甜味超标
甜味超标 2021-02-05 04:19

Simple question:
If you have a string x, to initialize it you simple do one of the following:

string x = String.Empty;  

or

5条回答
  •  不知归路
    2021-02-05 04:55

    You may use default construct to set it to whatever that Type's default is.

    The default keyword allows you to tell the compiler that at compile time the default value of this variable should be used. If the type argument supplied is a numeric value (e.g., int, long, decimal), then the default value is zero. If the type argument supplied is a reference type, then the default value is null. If the type argument supplied is a struct, then the default value of the struct is determined by initializing each member field of the struct to zero for numeric types or null for reference types.

    Use something like :

    T data = default(T);

    For details, read : Initializing Generic Variables to Their Default Values

提交回复
热议问题