C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,997 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello anybody,
Is it possible to use a if in a switch?
switch (eingabe)
{
//Path check/create
if(!System.IO.Directory.Exists($@"{localappdata}\Liquid Aqua\API"))
{
System.IO.Directory.CreateDirectory($@"{localappdata}\Liquid Aqua\API");
}
break;
Hi Robin,
Yes, but you would still need to have the "case" statement, because otherwise, there's no point in using the "switch". Something like this:
switch (eingabe)
{
case "SomeValue of eingabe":
//Path check/create
if(!System.IO.Directory.Exists($@"{localappdata}\Liquid Aqua\API"))
{
System.IO.Directory.CreateDirectory($@"{localappdata}\Liquid Aqua\API");
}
break;
case "SomeOther Value if needed":
// do something
break;
}
Hope that helps.
Hello @RobinJ
If using C# 9 there is the switch expression, you can also use the following which you supply logic for each condition.
public static class Example
{
public static bool Demo(int item, string folder) => item switch
{
1 => Operations.DoSomething1(folder),
2 => Operations.DoSomething2(folder),
_ => Operations.DefaultSwitch()
};
}
public class Operations
{
public static bool DoSomething1(string folder)
{
if (Directory.Exists(folder))
{
return true;
}
else
{
Directory.CreateDirectory(folder);
return false;
}
}
public static bool DoSomething2(string folder) => /* do whatever*/ true;
public static bool DefaultSwitch() => false;
}
Here is a tad more robust example that shows returning a List with source in the following repository.
public static List<Employee> GetEmployeesWhereManagerHasYearsAsManager(this Person person) => person switch
{
Manager { YearsAsManager: >=4 } manager => manager.Employees,
Manager { YearsAsManager: 3 } manager => manager.Employees,
_ => null
};