Is it possible in C# to define a variable like so?
switch(var num = getSomeNum()) {
case 1: //Do something with num
break;
default: break;
}
public static int GetSomeNum() => 3;
The documentation says that
In C# 6, the match expression must be an expression that returns a
value of the following types:
a char.
a string.
a bool.
an integral value, such as an int or a long.
an enum value.
Starting with C# 7, the match expression can be any non-null
expression.
To answer your question,
Yes you can switch on an int, e.g.
int myInt = 3;
switch(myInt)
Yes you can switch on the result of a method that returns an it, e.g.
int GetMyInt()
{
// Get my Int
}
switch(GetMyInt())
Yes you can switch on variable populated with a method result, e.g.
int GetMyInt()
{
// Get my Int
}
int myInt = GetMyInt();
switch(myInt)
No you can't do it like that.
Related
I know that case cannot work with non-constant values, but what should I do if its impossible to make a constant? thats my case: we have three variables, need to find that, one that will correspond to the value of the switch condition, but how to do this if the case is not able to work with non-constants? are there any workarounds?
float value = 4;
float number1 = 3, number2 = 6, number3 = 4;
switch (value)
{
case number1:
{
break;
}
case number2:
{
break;
}
case number3:
{
break;
}
}
here is the oversimplified example, and yes, you can easily do this using if/else if, but what if the number of values will be 100? what to do in that case?
One approach is to use an inverted Dictionary, where the key is the value and the value the key. Something like this:
var d = new Dictionary<int, int>();
d.Add(3, 1);
d.Add(6, 2);
d.Add(4, 3);
int keyPtr = d[value];
switch (keyPtr):
{
case 1:
//do something.
break;
case 2:
//do something else.
break;
case 3:
//do something different.
break;
}
Obviously this is simplified, and I have used int not float, but the same applies to any type. Using this technique,
your n variables, become the first n items in the Dictionary. In practice at the very least, you should check if your given value exists as a key in the Dictionary. It should help you in the right direction.
If you simply want to check whether your value variable equals to at least one of the variables number1, number2, number3, you could create an array of those numbers, say numbers[] and then create a method such as:
private bool checkValue(float value, float[] numbers) {
foreach (float num in numbers) {
if (num == value) return true;
}
return false;
}
This solution fits any number of elements in your numbers array.
If you want you can also use a List<float> instead of an array, so you could dynamically add more and more elements (Without a fixed size).
I want to ask something about ref modifier.
What I know and understand:
With method that use ref modifier, there will be no copy of data as with passing by value, but parameter will have directly access to argument value. Basically said, all you done in method’s scope will act same as if you would done it with argument (passed variable) in caller’s scope.
and I want to ask what is exactly stored in parameter with ref modifier:
When I pass argument to method with ref modifier, will parameter contain reference to value of argument? or is it something else?
Thank you for your answers
When you have a parameter with the ref attribute, it passes the argument by reference and not value. That means a new copy of the variable is not being made, rather a pointer to the original is being used within your function.
public void Foo()
{
var x = 0;
Bar(x); // x still equals 0
Bar(ref x); // x now equals 1
}
public void Bar(ref int x)
{
x = 1;
}
public void Bar(int x)
{
x = 1;
}
Let's say we have this method:
public void DoSomething(int number)
{
number = 20;
}
And we use it:
var number = 10;
DoSomething(number);
Console.WriteLine("Our number is: {0}", number);
The output would be Our number is: 10. Our number does not become 20.
That's because we're passing by value, so we're basically taking a copy of number before we change it.
However, if we pass by reference instead:
public void DoSomething(ref int number)
{
number = 20;
}
And then use our method:
var number = 10;
DoSomething(ref number);
Console.WriteLine("Our number is: {0}", number);
The output then becomes Our number is: 20
This is my enumeration:
enum Stations
{
Central,
RomaStreet,
Milton,
Auchenflower,
Toowong,
Taringa,
Indooroopilly
};
this is my code:
static string DepartureStation(){
string departStationinput;
string departStation;
if (departStation == null){
Console.WriteLine("Please Enter one of the names of the stations listed above! ");
departStationinput = Console.ReadLine(); // Gets String
departStation = departStationinput.ToUpper(); // Converts String into UPPER CASE
/*Need to check if the string is matched in the ENUM and return a variable/Value for it*/
}
return departStation;
}
You can use Enum.IsDefined method then parse the value:
if(Enum.IsDefined(typeof(Stations), departStationinput)
{
var value = Enum.Parse(typeof(Stations), departStationinput);
}
Or you can use Enum.TryParse directly:
Stations enumValue;
if(Enum.TryParse(departStationinput, out enumValue))
{
}
If you want to ignore case sensitivity there is also another overload that you can use.
First of all, about integer position, it depends on what you expect as integer position:
It may be the enumeration integer value.
The index of the enumeration value.
If you want the integer value, it's about doing this:
int value = (int)Enum.Parse(typeof(Stations), "Central"); // Substitute "Central" with a string variable
In the other hand, since enumeration values may not be always 1, 2, 3, 4..., if you're looking for the index like an 1D array:
int index = Array.IndexOf
(
Enum.GetValues(typeof(Stations))
.Select(value => value.ToString("f"))
.ToArray(),
"Central"
);
var val = Enum.Parse(typeof(YourEnumType),name);
in java its possible to do something like this
class {
final int x = Random.randomInt();
final int y = Random.randomInt();
}
...
switch (intVariable)
{
case x: break;
case y: break;
}
as long as generateInt is final, this compiles.
is there an equivalent in C#?
edit: you might ask why i dont use concrete values or enums, but i have my reasons why the values are be random. ;)
with const you can't do that, it has to be a compile time constant.
You may use readonly, something like:
public class yourClass
{
public readonly int x = generateInt();
public static int generateInt()
{
return DateTime.Now.Millisecond; // or any other method getSomeInt();
}
}
EDIT:
Since the question is now edited and asks with reference to case expression in switch statement. You can't specify a variable or readonly in the case statement, it has to be constant expression/compile time constant.
From MSDN - Switch
Each case label specifies a constant value.
You may use if...else for your scenario.
In C#, when defining a public method like:
public int myMethod(String someString)
{
//code
}
What does the int indicate apart from the type integer? What confuses me is that the method is using a String as arguments in this case.
It is the return type of the method. In this case a 32-bit signed integer with a range of
-2,147,483,648 .. +2,147,483,647
It corresponds to the .NET type System.Int32. int is just a handy C# alias for it.
You would return a value like this
public int Square(int i)
{
return i * i;
}
And you could call it like this
int sqr = Square(7); // Returns 49
// Or
double d = Math.Sin(Square(3));
If you do not need the return value, you can safely ignore it.
int i;
Int32.TryParse("123", out i); // We ignore the `bool` return value here.
If you have no return value you would use the keyword void in place of the type. void is not a real type.
public void PrintSquare(int i)
{
Console.WriteLine(i * i);
}
And you would call it like this
PrintSquare(7);
The method in your example accepts a string as input parameter and returns an int as result. A practical example would be a method that counts the number of vowels in a string.
public int NumberOfVowels(string s)
{
const string vowels = "aeiouAEIOU";
int n = 0;
for (int i = 0; i < s.Length; i++) {
if (vowels.Contains(s[i])) {
n++;
}
}
return n;
}
It stands for "integer", and it means the method returns an integer number of 32 bits, also known in C# as Int32.
As previously stated, it's what the method returns.
For example:
public string x()
{
return 5;
}
Would error. 5 is definitely not a string!
public int x()
{
return 5;
}
Would be correct; since 5 can be considered an int (Short for integer, which is, basically, just a number which cannot have a decimal point. There's also float, double, long and decimal, which are worth reading about)
There must be no way of it not returning, for example, if you do:
public int x()
{
if (false)
{
return 5;
}
}
It will error because if the expression is false (It is of course) it won't be returning an int, it won't return anything.
If you use the keyword void, it means it does not return anything. Ex:
public void x()
{
someFunction("xyz");
}
It's fine that it doesn't return as it's a void method.
I don't think you're new to programming judging by your reputation, but just in case, when you return something you pass it back from the method, for example:
int x;
public int seven()
{
return 7;
}
x = seven();
x will become the return value of the function seven.
Note that the 'dynamic' type works here:
public dynamic x(int x, int y)
{
if (x == y)
{
return "hello";
}
return 5
}
But if you're new to C# don't get caught up in dynamic typing just yet. :)
It is the type of the return value.
Everyone is correct here but the definition from msdn:
"Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32.MinValue constant) through positive 2,147,483,647 (which is represented by the Int32.MaxValue constant. The .NET Framework also includes an unsigned 32-bit integer value type, UInt32, which represents values that range from 0 to 4,294,967,295."
Found here on MSDN: Int32 Structure
I suggest you read the documentation found in the link above. It is extremely useful.