Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default value for generic type in c# [duplicate]

The docs for Dictionary.TryGetValue say:

When this method returns, [the value argument] contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.

I need to mimic this in my class. How do I find the default value for type T?


How can this question be modified to make it show up in the search?

Exact duplicate of Returning a default value. (C#)

like image 274
BCS Avatar asked Dec 15 '08 22:12

BCS


People also ask

Can a generic type be null?

This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. Also, we cannot simply return null from a generic method like in normal method.

What is default value of string in C#?

The object and string types have a default value of null, representing a null reference that literally is one that does not refer to any object.

What is generic in C?

Generics are syntax components of a programming language that can be reused for different types of objects. Typically, generics take the form classes or functions, which take type(s) as a parameter. Generics are also commonly referred to as templates , and in C++ are officially called templates.


1 Answers

You are looking for this:

default(T); 

so:

public T Foo<T>(T Bar) {    return default(T); } 
like image 60
Nathan W Avatar answered Sep 22 '22 11:09

Nathan W