Reputation: 13416
I'm very new LINQ, and I've a question regarding it here.
I have this very simple class here for demonstration purposes:
public class CurrencyPair
{
public string? cultureCode;
public string? currencyName;
public CurrencyPair(string iCultureCode, string iCurrencyName)
{
cultureCode = iCultureCode;
currencyName = iCurrencyName;
}
public CurrencyPair()
{
cultureCode = "";
currencyName = "";
}
}
Then I have a List of instances of the above Class:
static List<CurrencyPair> currencyPairs;
Now I'm trying to do this:
public List<string> GetCurrencyNames()
{
return (from c in currencyPairs select c.currencyName).Distinct().ToList();
}
However I get this error:
The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
If I remove the ?
for cultureCode
and currencyName
in the class definition, this error goes away.
So how can I use nullable strings in LINQ queries .. ?
Upvotes: 1
Views: 125
Reputation: 223282
string
is already a reference type, it can hold null
, you don't have to use string?
The error is indicating that as well:
The type 'string' must be a non-nullable value type....
You can only use Nullable<T>
with value types.
Represents a value type that can be assigned null.
You are trying to declare field with string?
which is equal to Nullable<string>
, but this can only be done with value types.
In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null
.
Upvotes: 8