Removing ambiguity when passing null to a function in C# [duplicate] - c#

This question already has answers here:
Overloading null ambiguity
(2 answers)
Closed 7 years ago.
I have two functions which differ only in their second parameter.
Example:
public IEnumerable<Thing> Get(string clause, List<Things> list)
{
}
public IEnumerable<Thing> Get(string clause, List<OtherThing> list)
{
}
I want to call the first instance of this function, but I want to pass null as the second parameter. Is there a way to specify the "type" of null?

Cast the null literal:
Get("", (List<Things>)null)
store it in a variable first:
List<Things> list = null;
Get("", list);
Use reflection. (I'm not going to show an example because it's needlessly complicated.)

Related

How do I pass ToUpper or ToLower to a method as a parameter? [duplicate]

This question already has answers here:
Pass Method as Parameter using C#
(13 answers)
Passing methods as parameter vs calling methods directly
(5 answers)
C# method as parameter
(4 answers)
Pass method as parameter [duplicate]
(4 answers)
Closed 1 year ago.
I searched all over for a way to pass ToUpper or ToLower as a parameter. I looked at actions, I looked at delegates, I looked at extension methods, and I looked at Microsoft documentation. The closest answer I got was: Passing an extension method to a method expecting a delegate. How does this work?, but that didn't really explain how to do it. I am writing this question in case someone else runs across a similar problem. For example, you can't pass string.ToLower() as a parameter.
The issue is figuring out:
How to call string.toLower() as a delegate?
Example of what I want to be able to do:
orderItems.GetContatenatedModdedNames(string.ToLower());
orderItems.GetConcatenatedModdedNames(string.ToUpper());
The example idea is to be able to pass in ToLower() or ToUpper() as a parameter.
Here is an example of how to do it... it involved passing an anonymous function.
public static string GetConcatenatedNames(this ICollection<OrderItem> orderItems, string separater = ",", Func<string, string> myFunc = null)
{
if (myFunc == null)
{
myFunc = x => x.ToLower();
}
var productNames = orderItems?.Select(x => x.Product)?.Select(x => myFunc(x.ProductName));
if (productNames == null)
{
return null;
}
return string.Join(separater, productNames);
}
To call this:
var upperCaseNames = orderItems.GetConcatenatedConcessionNames(myFunc: x => x.ToUpper());

int? version available for String.IsNullOrWhiteSpace [duplicate]

This question already has answers here:
Nullable types: better way to check for null or zero in c#
(13 answers)
Closed 5 years ago.
Our application requires int? variables. I'm often checking both to make sure not null and not 0 and it does get lengthy.
Is there an out of the box version of String.IsNullOrWhiteSpace() or String.IsNullOrEmpty() for int?
Maybe this would require an extension method?
If there even was or when someone makes one, would something like this considered bad practice?
I don't think so but it's easy to write your own:
[Pure]
public static bool IsNullOrDefault<T>(this T? pValue)
where T : struct {
return pValue == null || pValue.Value.Equals(default(T));
// or as suggested in comments (tested)
return pValue == null || EqualityComparer<T?>.Default.Equals(pValue, default(T));
}

Question mark '?' given in arguments of a method [duplicate]

This question already has answers here:
What is the purpose of a question mark after a value type (for example: int? myVariable)?
(9 answers)
What does the question mark in member access mean in C#?
(2 answers)
Closed 6 years ago.
I have a code containing a class with the following method:
public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid){...}
My question is what does the question mark there do? My guess it has something to do with overloading since there's another overload method of AddEvent but I'm not sure...
Simple, this isn’t C++ code. It’s C#, where ? denotes a nullable value type. I.e. a value type that can also be null. int? is a shortcut for Nullable<int>.
Usually a simple type like int cannot be null, using ? allows the int to have a null value like an object.
Inside the function, you need to check to see if eventId is valid to use. You can do this by checking HasValue or equal to null. If you try to use it without checking, and it is null, then it will throw System.InvalidOperationException:
public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid)
{
// use HasValue
if (eventId.HasValue)
eventId++;
// or check for null
if (eventId != null)
eventId++;
}

Unable to pass List<char> to List<object> as a parameter? [duplicate]

This question already has answers here:
Why covariance and contravariance do not support value type
(4 answers)
Closed 7 years ago.
So I have a method in my code where one of the parameters is a IEnumerable<object>. For clarity purposes, that will be the only parameter for the example. I was originally calling it with a variable that was a List<string>, but then realized I only needed those to be chars and changed the signature of the variable to List<char>. Then I received an error in my program saying:
Cannot convert source type 'System.Collections.Generic.List<char>'
to target type 'System.Collections.Generic.IEnumerable<object>'.
In code:
// This is the example of my method
private void ConversionExample(IEnumerable<object> objs)
{
...
}
// here is another method that will call this method.
private void OtherMethod()
{
var strings = new List<string>();
// This call works fine
ConversionExample(strings);
var chars = new List<char>();
// This will blow up
ConverstionExample(chars);
}
The only reason that I could possibly think of as to why the first will work, but the second won't is because a List<char>() is convertible to a string? I don't really think that would be it, but that's the only long-shot guess that I can make about why this doesn't work.
Generic argument covariance doesn't support value types; it only works when the generic argument is a reference type.
You can either make ConversionExample generic and accept an IEnumerable<T> rather than an IEnumerable<object>, or use Cast<object> to convert the List<char> to an IEnumerable<object>.
This would be my solution:
// This is the example of my method
private void ConversionExample<T>(IEnumerable<T> objs)
{
...
}
// here is another method that will call this method.
private void OtherMethod()
{
var strings = new List<string>();
// This call works fine
ConversionExample<string>(strings);
var chars = new List<char>();
// This should work now
ConversionExample<char>(chars);
}

string to Enum in c# [duplicate]

This question already has answers here:
Search for a string in Enum and return the Enum
(13 answers)
Closed 9 years ago.
I need to assign a string to a Enum value. My scenario and code below
Am accessing a webservice method say addWhere(int i ,int j,Comparison)
Where Comparison is of type Enum.
Am fetching value from UI and having it in a string
string strComparison= "AND"; or
string strComparison= "OR"
i need to set these values to ENUM. I tried the below code
addWhere(2 ,3,Enum.Parse(typeof(Comparison),strComparison))
But didnt worked. What is the way to solve this or any alternate methods ?
Thanks
Looks like your missing the return cast i.e.
(Comparison)Enum.Parse(typeof(Comparison), strComparison);
Enum.Parse returns an object were as your addWhere method is expecting a Comparison type value.
You must cast the result of Enum.Parse to the correct type:
addWhere(2, 3, (Comparison)Enum.Parse(typeof(Comparison), strComparison));
You can do something like:
Comparison comparison;
if(Comparison.TryParse(strComparison, out comparison))
{
// Work with the converted Comparison
}
As said in earlier posts, you might be missing type casting.
enum Comparision
{
AND,
OR
}
class Program
{
static void Main(string[] args)
{
Comparision cmp = (Comparision)Enum.Parse(typeof (Comparision), "And", true);
Console.WriteLine(cmp == Comparision.OR );
Console.WriteLine(cmp == Comparision.AND);
}
}

Categories

Resources