In a WPF project I got I have a class called IHavePassword and in another file a listener for a button like this
private void DoLogin(object parameter)
{
if (parameter is IHavePassword passwordContainer)
{
...
}
}
My question relates to the if statement after the "is" keyword, what is it doing there? Is it comparing the method parameter to an "IHavePassword" class new instance?
Great question you have asked, in C# there is a concept called pattern matching. so the primary Author is trying to check if parameter coming is compatible with IHavePassord. if this is compatible the variable then becomes passwordContainer.
This link to microsoft documentation will help.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
private void DoLogin(object parameter)
{
// expr (parameter) is type(IHavePassword) varname (passwordContainer)
if (parameter is IHavePassword passwordContainer)
{
// if true you can now have access to passwordContainer.
}
}
Hope this helps. Thanks
What this does, is to let you check if the object is of type IHavePassword and if it is, you can use it afterwards by using the variable passwordContianer.
This is called pattern matching, which you can learn more about here:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
This is called "Pattern Matching". It was added in C# 7.0.
https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching#the-is-type-pattern-expression
From the article:
the is expression both tests the variable and assigns it to a new variable of the proper type
So in your question, the variable passwordContainer is the variable declaration set aside for the is being true.
this should help
private void Simple(object parameter)
{
if (parameter is int)
{
//do something which does not need the type
Something();
//this line will not work as it does number not exist, see below SimpleOther
//var newTotal = 1 + number;
//this line does not work as object is not a int
//var newTotal = 1 + parameter;
}
}
private void SimpleOther(object parameter)
{
if (parameter is int number)
{
//this works as it know its type is int and 1 is an int.
var newTotal = 1 + number;
}
}
private void CommonNormalUsage(object parameter)
{
if (parameter is SomeClass someClass)
{
//where SomeClass as a methood called AddSomethingSpecialMethod
someClass.AddSomethingSpecialMethod();
}
//this is done so the runtime knows what type parameter is and con only work
//with an instance which has been "cast" to that type
}
Related
Want feedback if i`m correct here?
Use void if you are not returning anything in a method,
otherwise
Name your data types used in the method criteria before method name.
use Return in the method before the calculation or output.
So something like this.
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
What if my method has ints and doubles?
Do I write as follows? (another words do I have to mention every type i`m using prior to the method name?
static int double myMethod (int x, double y)
Even with that I dont know when is a method void? It seems my methods all return values.
Isnt the following returning the values of the arguments? So why should I label it void?
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 20);
MyMethod("Jenny", 25);
MyMethod("Tom", 31);
}
I can only think that a void means there is no new calculation being done in the actual method body, passing arguments into a method and spitting them out for user viewing does not mean its "returning a value", I dont know what i`m talking about.
Let's be completely clear about what these bullets mean.
Use void if you are not returning anything in a method, otherwise
In this context, "return" means that the method provides an output that can be assigned to a variable by the caller. For example
int Return10()
{
return 10;
}
...allows the caller to do this:
int x = Return10();
Console.WriteLine(x); //Outputs "10"
A method should "return" void when its results cannot be assigned. For example, if the results are printed on the screen.
void Print10()
{
Console.WriteLine("10"); //Prints 10 to the screen
}
...which allows the caller to do this:
Print10();
You cannot assign it because it doesn't return anything. This doesn't work:
int x = Print10(); //Compiler error
Name your data types used in the method criteria before method name.
A method can return exactly one value or object. So "types" here is wrong. You can only specify one type.
Use return in the method before the calculation or output.
This is a little misleading. The return keyword should be followed by an expression which can be assigned.
int Return10()
{
return 10 + 10; //Is okay because it's an expression and could be assigned
}
int Return10()
{
var x = 10 + 10;
return x; //This is also okay; in fact it does exactly the same thing as the previous example
}
int Return10()
{
return Console.WriteLine("10"); //Compiler error; can't be assigned to anything.
}
By the way, a method can also output something and return it:
int WriteAndReturn10()
{
int x = 10;
Console.WriteLine(x);
return x;
}
I am going to address the following
What if my method has ints and doubles? Do I write as follows?
(another words do I have to mention every type i`m using prior to the
method name?
There are no built in ways or syntax to return more than one type from a method as the return parameter.. This is basically historical and has been this way since dinosaurs roamed the earth.
However, there are lots of options that achieve the same result. For instance, you could use a custom struct, you could use out parameters, you could use a class, or a delegate parameter of some kind. However, a modern succinct approach might be to use a Value Tuple:
static (int someInt, double someDouble) myMethod (int x, double y)
{
return (x,y);
}
Fun Fact : even though this looks like you a returning more than one type, you are actually just invoking a special syntax that wraps your return parameters in a single type of struct
Usage
var result = myMethod(1,2.2);
Console.WriteLine(result.someInt);
Console.WriteLine(result.someDouble);
Or if you want to get fancy, you can use the newer deconstructed syntax
var (someInt, someDouble) = myMethod(1,2.2);
Console.WriteLine(someInt);
Console.WriteLine(someDouble);
Additional Resources
return (C# Reference)
Methods (C# Programming Guide)
Tuple types (C# reference)
out parameter modifier (C# Reference)
ref (C# Reference)
Using Delegates (C# Programming Guide)
C# 8 introduced nullable reference types, which is a very cool feature. Now if you expect to get nullable values you have to write so-called guards:
object? value = null;
if (value is null)
{
throw new ArgumentNullException();
}
…
These can be a bit repetitive. What I am wondering is if it is possible to avoid writing this type of code for every variable, but instead have a guard-type static void function that throws exception if value is null or just returns if value is not null. Or is this too hard for compiler to infer? Especially if it's external library/package?
There are a few things you can do.
You can use [DoesNotReturnIf(...)] in your guard method, to indicate that it throws if a particular condition is true or false, for example:
public static class Ensure
{
public static void True([DoesNotReturnIf(false)] bool condition)
{
if (!condition)
{
throw new Exception("!!!");
}
}
}
Then:
public void TestMethod(object? o)
{
Ensure.True(o != null);
Console.WriteLine(o.ToString()); // No warning
}
This works because:
[DoesNotReturnIf(bool)]: Placed on a bool parameter. Code after the call is unreachable if the parameter has the specified bool value
Alternatively, you can declare a guard method like this:
public static class Ensure
{
public static void NotNull([NotNull] object? o)
{
if (o is null)
{
throw new Exception("!!!");
}
}
}
And use it like this:
public void TestMethod(object? o)
{
Ensure.NotNull(o);
Console.WriteLine(o.ToString()); // No warning
}
This works because:
[NotNull]: For outputs (ref/out parameters, return values), the output will not be null, even if the type allows it. For inputs (by-value/in parameters) the value passed is known not to be null when we return.
SharpLab with examples
Of course, the real question is why you want to do this. If you don't expect value to be null, then declare it as object?, rather than object -- that's the point of having NRTs.
There is a Guard Clauses library by Steve Ardalis that I think can help you with this situation.
You can do things like:
Guard.Against.Null (throws if input is null)
Guard.Against.NullOrEmpty (throws if string or array input is null or empty)
Guard.Against.NullOrWhiteSpace (throws if string input is null, empty or whitespace)
Guard.Against.OutOfRange (throws if integer/DateTime/enum input is outside a provided range)
Guard.Against.OutOfSQLDateRange (throws if DateTime input is outside the valid range of SQL Server DateTime values)
Guard.Against.Zero (throws if number input is zero)
In this blog post Jason Roberts made a quick explanation of the library too.
There is another Guard Class in the Microsoft.Toolkit.Diagnostics namespace but probably is not viable in all the use cases that will depend if wanna add that dependency to the project or not.
I am hoping that this is a simple question, and it's just my brain that is missing that final link. And if there is another q&a elsewhere, please point me there and close this... but I couldn't find it anywhere.
Here is the gist:
I have a class with a method with optional parameters, something along the lines of
public class Test
{
public void Method(string required, string someoptionalparameter="sometext", string anotheroptionalparameter="someothertext")
{
// do something here with the parameters
}
}
So far, so good.
Now, I am going to instantiate the class and call the method in my code:
...
Test.Method("RequiredString");
and that will work. If I provide optional parameters, it will still work.
But how do I handle a scenario, where I do not know if an optional value is actual provided. So for instance:
...
Test.Method(requiredString,optionalString1,optionalString2);
...
What if I do not know, if the optionalString1 and optionalString2 have a value or not? Do I then need to write an override for every scenario, along the lines of...
if (optionalString1.isEmpty() && optionalString2.isEmpty())
{
Test.Method(requiredString);
}
else if ((!optionalString1.isEmpty() && optionalString2.isEmpty())
{
Test.Method(requiredString, optionalString1);
}
else if...
There has to be another way, and I bet it is simple and I am just having one of those Fridays... Is there something like...
Test.Method(requiredStrinig, if(!optionalString1.isEmpty())...
You should invert the logic - have those optional parameters be null and then do checks in method. So in your case method should be something like:
public void Method(string required, string opt1 = null, string opt2 = null)
{
opt1 = opt1 ?? "some default non-null value if you need it";
opt2 = opt2 ?? "another default value, this one for opt2";
// for those not knowing what it does ?? is basically
// if (opt1 == null) { opt1 = "value"; }
//... rest of method
}
Then calling that method will be easier in outside code and the logic within the method will be able to handle null cases. Outside of method you don't need to worry about those extra parameters, i.e. you can call the method any way you want, like:
Test.Method(requiredString);
Test.Method(requiredString, "something");
Test.Method(requiredString, null, "something else");
Also as #Setsu said in comment you could do this to avoid passing null as second parameter:
Test.Method("required", opt2: "thanks #Setsu");
Use overloads instead, it gives you better semantics and in case you guess the parameters from client code you'd be sure what overload to use, besides, you'll have all the machinery in one place, check out this technique, hope this helps, regards.
class Program {
static void Main(string[] args) {
Work("Hi!");
}
private static void Work(String p1) {
Work(p1, null, null);
}
private static void Work(String p1, String p2) {
Work(p1, p2, null);
}
private static void Work(String p1, String p2, String p3) {
if ( String.IsNullOrWhiteSpace(p2) ) p2 = String.Empty;
if ( String.IsNullOrWhiteSpace(p3) ) p3 = String.Empty;
Console.WriteLine(String.Concat(p1, p2, p3));
}
}
Optional parameters, are, well, optional. They seem to be a way to reduce the number of overloads you have for a method. If you receive all three parameters, you will have to decide if the second or third parameters are empty and need set to their "default" values.
My suggestion is you call your method with three strings and decide in the method if you have to change the values for string two and three. I would probably use a const or readonly instead of the default values.
Part of my software is using reflection. The issue I am having is that while I can get the type of the property, I cannot convert the string value using the Type from the PropertyInfo. This is the reason why i am using t in the sample code.
The below code demonstrates the issue with the error message as a code comment. The syntax error is on the t. how can I fix this problem? thanks
class Program
{
static void Main(string[] args)
{
Type t = typeof(Letters);
Letters letter = "A".ToEnum<t>(); //-- Type or namespace expected.
}
}
public enum Letters { A, B, C }
//-- This is a copy of the EmunHelper functions from our tools library.
public static class EnumExt
{
public static T ToEnum<T>(this string #string)
{
int tryInt;
if (Int32.TryParse(#string, out tryInt)) return tryInt.ToEnum<T>();
return (T)Enum.Parse(typeof(T), #string);
}
public static T ToEnum<T>(this int #int)
{
return (T)Enum.ToObject(typeof(T), #int);
}
}
Solution:
The following works because when the value is set using reflection, the actual type of Enum is accepted. Where myObject.Letter = result is not.
Type t = currentProperty.PropertyType;
Enum result = Enum.Parse(t, #string) as Enum;
ReflectionHelper.SetProperty(entity, "LetterPropertyName", result);
Thank you all for your help.
Enum.Parse(t, #string) as Enum;
That accomplishes the same thing as the solution you posted.
To be able to call a generic method, the type must be known at compile time. Your use is invalid syntax.
To be able to call your method, you'll have to use reflection to get a reference to the correct generic function so you may call it.
public static object ToEnum(this string s, Type type)
{
var eeType = typeof(EnumExt);
var method = eeType.GetMethod("ToEnum", new[] { typeof(string) })
.MakeGenericMethod(type);
return method.Invoke(null, new[] { s });
}
Then you could call it:
Letters letter = (Letters)"A".ToEnum(t);
p.s., I strongly urge you to change your variable names to something else. Just because you can name your variables as keywords, doesn't mean that you should.
I'm not an expert with reflection, but this works:
static void Main(string[] args)
{
Type t = typeof(Letters);
MethodInfo info = typeof(EnumExt).GetMethod("ToEnum", new Type[] { typeof(string) });
var method = info.MakeGenericMethod(new Type[] { t });
var result = (Letters)method.Invoke(null, new [] { "A" });
Console.ReadLine();
}
I think your question can be understood in two ways:
i) you want to fix a syntax error
ii) you need a working implementation for the function you provide
For i), I would suggest you to change:
Letters letter = "A".ToEnum<t>()
into
Letters letter = "A".ToEnum<Letters>()
because generics are solved at compile time, hence you cannot use variables as parameters.
For ii), you may change the way you provide the type argument, from "generic" argument to "normal" argument (as proposed by Jeff Mercado). By doing so the prototype of your function becomes:
public static T ToEnum(this string #string, Type t)
I conclude with two remarks:
reflection is VERY slow to my experience. I once wrote an assembly parser making extensive use of reflection on enums for register names. It used to run for minutes (which used to make VS debugger complain about non-responsiveness) when an equivalent version without any reflection used to execute in less than 10 seconds.
as Jeff Mercado pointed out, I cannot see any good reason for you to use the same vocable for type names and variable names
Hello
I'm having an error with this code:
"The out parameter 'o_BlockingSquaresArr' must be assigned to before control leaves the current method"
Now this error paints each return statement of each method apart from the last one with red..
I don't understand what is the problem regarding my specific code
Please help me,
Thanks in Advance
internal bool isLegalMove(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
bool result;
if (m_GameBoard[i_Move.RowIndex, (int)i_Move.ColIndex].Coin != null)
{
result = false;
m_MessageBuffer = "You have enterd a square which is already
occupied, please try again...";
m_ErrorFlag=true;
}
else
{
result = checkIfThereIsAtLeastOneSeqInOneDirection(i_Move,out o_BlockingSquaresArr);
}
return result;
}
internal bool checkIfThereIsAtLeastOneSeqInOneDirection(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
const int k_EightDirections = 8;
bool isSequenceFound, finalRes = false;
for (int i = 1; i <= k_EightDirections; i++)
{
isSequenceFound = checkOpponentSequenceInDirection(i_Move, (eDirections)i, out o_BlockingSquaresArr);
if (isSequenceFound)
{
finalRes = true;
}
}
return finalRes;
}
internal bool checkOpponentSequenceInDirection(Square i_Move, eDirections i_Direction, out List<Square> o_BlockingSquaresArr)
{
//I've shortened this code only relevant things
Square o_AdjacentSquare = new Square();
adjacentCoin = doSwitchAndRetrieveAdjacentCoin(i_Move, i_Direction, out o_AdjacentSquare);
// ...
if (isThereAnOpponentSequence)
{
o_BlockingSquaresArr.Add(o_AdjacentSquare);
}
return isThereAnOpponentSequence;
}
As the compiler error says, an out parameter has to be definitely assigned before any non-exceptional return of a method. I can't see any assignment to o_BlockingSquaresArr anywhere. Why are you even declaring it as an out parameter to start with?
An out parameter must be assigned a value before the method returns. In your isLegalMove method, o_BlockingSquaresArr is only assigned in the else block, so the compiler detects there are some cases where it is not initialized. You must make sure that all code paths in the method assign a value to o_BlockingSquaresArr before returning
You need to assign something to the out parameter in every execution path. In your case, you forget that in one case. Simply assign a default value of the beginning of the method so you don't run into it.
I can't tell you where as you didn't include the method name it is happening in.
In the IsLegalMove function, you need to assign a value to the o_BlockingSquaresArr variable
You need to assign something to out parameters in every (normally terminating) codepath. And you don't do that.
For example in some functions you only assign to the parameter inside the for-loop. And if the loop has 0 iterations this will never happen.