I'm trying to code a Linq MinBy extension method
public static class Extensions
{
public static T MinBy<T>(this IEnumerable<T> source, Func<T,int> selector)
{
T min;
int? minKey = null;
foreach (var x in source)
{
var key = selector(x);
if (minKey == null || key < minKey)
{
minKey = key;
min = x;
}
}
if (minKey == null)
{
throw new ArgumentException("source should not be empty");
}
return min;
}
}
I think my logic is correct and readable. But I get a build error
Use of unassigned local variable 'min'
What can I do about this? Can I test if the variable is assigned?
Clarification: A MinBy function can answer the following question. Which of the numbers [-5, -2, 3] has the smallest square?
> new List<int>{-5,-2,3}.MinBy(x => x*x)
-2
.NET's Min function answers a different question (which is the smallest of the squares)
> new List<int>{-5,-2,3}.Min(x => x*x)
4
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
You need a default value for min
like this:
T min = default(T);
You can read more about default()
on MSDN:
Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.
Add a default value for min
:
T min = default(T);
The reason it's complaining is that the compiler cannot verify that min
will have been assigned a value before it's used in the return min;
line. An unassigned local variable cannot be referenced, and so the compiler generates an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With