Inline conditional c# - next best solution? - c#

It seems the compiler is not going let this syntax fly.
void main()
{
foo(false?0:"");
}
void foo(int i) {return;}
void foo(string s) {return;}
The only other way I can see of fixing this is something as follows:
void bar(object o)
{
if (o is string){//do this}
else{//im an int, do this}
}
Anyone have any better ideas?

You cannot use a method with a void return type in a ternary expression in this way. End of story.
To understand why this is, remember what the ternary operator actually does -- it evaluates to the following:
(condition ? [true value] : [false value])
What this implies is that the following code:
int x = a ? b : c;
Must be rewritable to:
int x;
if (a)
{
x = b;
}
else
{
x = c;
}
The two above are logically identical.
So how would this work with a method with void as its return type?
// Does this make sense?
int x = condition ? foo(s) : foo(i);
// Or this?
if (condition)
{
x = foo(s);
}
else
{
x = foo(i);
}
Clearly, the above is not legal.
That said, others' suggestions would otherwise be valid if only your foo overloads returned a value.
In other words, if your signatures looked like this:
object foo(string s);
object foo(int i);
Then you could do this (you're throwing away the return value, but at least it'll compile):
object o = condition ? foo(0) : foo("");
Anyway, the ol' if/else is your best bet, in this case.

The method call of foo is determined at compile time, so it cannot call a different method (or overload) based on the result of evaluating the condition. Instead, try something like this:
condition ? foo(0) : foo("")
This way, the compiler will succeed in performing overload resolution and will resolve the first call to foo(int) and the second call to foo(string).
EDIT: As noted by other, you cannot use the ?: operator as a statement, nor can you use methods which return void in it. If your actual methods return compatible types, you could do something like:
int result = condition ? foo(0) : foo("");
If not, you must use an if:
if (condition)
foo(0);
else
foo("");

You're example doesn't make a whole lot of sense (the second example doesn't relate to the first).
I think the first example would be fine as:
void main()
{
foo("");
}
Since 0 will never be passed anyway (false is always false) and you can't use the inline conditional operator without an assignment somewhere (which your example is lacking).
As for the second way, that is probably how I would prefer to see it:
void bar(object o)
{
if(o is string) foo(o as string);
else foo((int)o);
}

I wouldn't pass in an object as a parameter. The int will be boxed, which is a little less efficient. Let the compiler figure out which method to call.
If you wrote:
foo(0);
foo("");
The appropriate method would be called. You could also write:
if (condition) {
foo(0);
} else {
foo("");
}
Depending on what you're trying to do (your example is lacking in a little detail).

If you use Inline if expressions in C#, both parts before and after the ":" have to be of the same type. What you are intending would never work.
Even if you like to do something like this:
DateTime? theTime = true ? DateTime.Now : null;
The compiler is not satisfied. In this case you will have to use:
DateTime? theTime = true ? DateTime.Now : default(DateTime?);

The conditional operator needs the true and false part to be of the same type. Which is why it's not compiling.
var x = condition ? 0 : "";
What type should the compiler choose for x? If you really want it to choose object make a cast or you could force it to choose dynamic in which case method overload would still work but you loose type safety. Both are however strong smells.
Having to test the runtime type is usually a design error but with the limited code (that will always have the same result) it's hard to help with a different approach that would require testing on runtime types

This:
foo(false?0:"")
Could be this:
false ? foo(0) : foo("")

Both results of the conditional operator must of the same type (or be implicitly convertible). So foo(false ? 0 : "") won't work because it is trying to return an Int32 and a String. Here's more information on the conditional operator.
The fix I would do is change that line to false ? foo(0) : foo("").
EDIT: Derp, can't use a conditional operator just in the open like that. They can only be used for assignments. You'll have to use a if/else block. Not in one line, but it'll do in a pinch.

Related

Aggregate: Seed with a null value [duplicate]

private static Matcher<T> EqualTo<T>(T item)
{
return new IsEqual<T>(item);
}
How do I modify the above method definition such that the following are valid/allowed.
EqualTo("abc");
EqualTo(4);
EqualTo(null); // doesn't compile. EqualTo<string>(null) does
Trying to port some Java code where null seems to be acceptable value for a T parameter.
Update
Thanks: for all the answers - especially Eamon and Jason. I didn't want the method calls to bother with type-inference. The following overload fixed it.
private static Matcher<object> EqualTo(object item)
{
return EqualTo<object>(item);
}
Actually the above question was a part of a larger puzzle. The end goal was for the following to work.
this.AssertThat(null, EqualTo(null));
this.AssertThat(null, Not(EqualTo("hi")));
this.AssertThat("hi", Not(EqualTo(null)));
Applied the same fix.. RFC. (Ignore the ugly extension method part - that's another problem. Wanted to have these methods in all test-fixtures without inheritance.)
public static void AssertThat<T>(this object testFixture, object actual, Matcher<T> matcher, string message = "")
{
AssertThat(anyObject, (T)actual, matcher, message);
}
public static void AssertThat<T, TSuper>(this object testFixture, T actual, Matcher<TSuper> matcher, string message = "") where T : TSuper
{
... check and assert
Consider the following method:
public bool IsNullString<T>(T item) {
return typeof(T) == typeof(string) && item == null;
}
Yes, this is a pathetically stupid method and using generics is pointless here, but you'll see the point in a moment.
Now consider
bool first = IsNullString<string>(null);
bool second = IsNullString<Foo>(null);
bool third = IsNullString(null);
In the first and second, the compiler can clearly distinguish the type of T (no inference is needed). In the third, how the compiler infer what T is? In particular, it can't distinguish between T == string and T == Foo, or any other type for that matter. Therefore, the compiler has to give you a compile-time error.
If you want to get around this, you either need to cast null
EqualTo((object)null);
or explicitly state the type
EqualTo<object>(null)
or define an overload
private static Matcher<object> EqualTo(object item) {
return new IsEqual<object>(item);
}
Not possible without explicitly specifying a T or doing a cast. Generics are compile time constructs and as such if the compiler can't figure out the type at compile time, then it won't compile (as you're seeing).
Since you can't do exactly what you are wanting to do, how about defining an EqualTo(object) overloaded method? That should allow your required syntax.
You may work around this limitation by using the following syntax:
EqualTo("abc");
EqualTo(4);
EqualTo(default(object));
//equivalently:
EqualTo((object)null);
default(T) is the value a field of type T has if not set. For reference types, it's null, for value types it's essentially memory filled with zero bytes (...which may mean different things for different types, but generally means some version of zero).
I try to avoid the null everywhere in my code nowadays. It hampers type inference elsewhere too, such as with the var declared field and in a ternary operator. For example, myArray==null ? default(int?) : myArray.Length is OK, but myArray==null ? null : myArray.Length won't compile.
Maybe implementing a non-generic EqualTo, which takes an Object as the argument type, would solve the issue of rewriting those code lines.

C# conditional operator - Call method if condition is true else do nothing

C# provides conditional operator (?:) that returns one of two values depending on the value of a Boolean expression. eg
condition ? first_expression : second_expression;
My question is can we use the same syntax to call a method when condition is true? and when condition is false then do nothing
public void Work(int? val)
{
var list = new List<int>();
//ofcourse line below doesn't work
//but is it possible to call method when condition is true and else do nothing
val.HasValue? list.Add(val.value) : else do nothing
}
the ?: has also been referred to as the ternary operator in the past. Ternary, for three. if this, then do this, else do this.
You have two expressions. If this, do this. This is exactly the point of an if statement. You are trying to fit your case into a construct that it isn't designed for. Don't do this.
Use the correct operation for the job:
if(val.HasValue)
{
list.Add(val.value)
}
The C# conditional operator is used to return a different value depending on the evaluation of a condition. It is not meant to be used to to be used the way you are trying to in your question. It should like be used this :
int test = i > 3 ? 0 : 1;
test will then equal 0 if i is less than (or equal to) 3, or test will equal 1 if 3 is greater than 3.
To do what you want you will have to use a regular if statement (which you can still write in one line by the way) :
if (val.HasValue) list.Add(val.value);
The conditional/ternary operator is supposed to return a value and that very specific value must be assigned back to somewhere.
So, in that case you can do that, yes. But, it would lead to bad design.
In a regular case, one would do this:
int x = (a > b) ? a : b;
Now, lets assume AddToList() is your desired method when the condition renders to true and DoRest() is the method you want to invoke if the condition turns out to false.
In the aforementioned case, you'd end up doing something like this:
int result = val.HasValue? AddToList(val.value) : DoRest();
Now you have to rely on result for finding out which one has been called (if you ever need that) and it's not very expressive and doesn't point to proper code design.
If you get a tad more adventurous you'd end up with :
var actionToInvoke = val.HasValue ? (Action)AddToList: (Action)DoRest;
actionToInvoke();
In any case, none of these lead to very readable code.
So, sticking with a simple if(val.HasValue) would be the simplest way to go here.
The way null conditional operator works is you have to return a value for the variable you are assigning it to. So if you would like a string value or something else other than void you can call the method with out any problem. But to call a void method you can use a delegate.
delegate void DelMethod();
void Method() { }
void MethodTwo() { }
private void MyMethod()
{
DelMethod x;
x = condition == true ? (DelMethod)Method : (DelMethod)MethodTwo;
}

how do I convert if else to one line if else?

how do i convert follow code to one line if else
if (data.BaseCompareId == 2)
report.Load(Server.MapPath("~/Content/StimulReports/MonthGroup.mrt"));
else
report.Load(Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
i try this code but did not work
data.BaseCompareId == 2
? report.Load(Server.MapPath("~/Content/StimulReports/MonthGroup.mrt"))
: report.Load(Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
Try with this instead :
string path = data.BaseCompareId == 2
? "~/Content/StimulReports/MonthGroup.mrt"
: "~/Content/StimulReports/YearGroup.mrt";
report.Load(Server.MapPath(path));
Since report.Load() returns a void, it wont work.
Edited version :
string s = data.BaseCompareId == 2
? "MonthGroup.mrt"
: "YearGroup.mrt";
report.Load(Server.MapPath("~/Content/StimulReports/" + s));
I am assuming report.Load returns a void, hence it "doesn't work". That said, why are you doing this? The first example is perfectly clear.
If you want are going to use ?: here use it so only the part which is actually different is in the branching statement:
string fileName = (data.BaseCompareId == 2) ? "MonthGroup.mrt" : "YearGroup.mrt";
report.Load(Server.MapPath("~/Content/StimulReports/" + fileName));
If you want to use a ternary operator, you can do:
report.Load(data.BaseCompareId == 2 ? Server.MapPath("~/Content/StimulReports/MonthGroup.mrt") : Server.MapPath("~/Content/StimulReports/YearGroup.mrt"));
Or (better):
report.Load(Server.MapPath(data.BaseCompareId == 2 ? "~/Content/StimulReports/MonthGroup.mrt" : "~/Content/StimulReports/YearGroup.mrt"));
(Or you could further exploit the similarity in the two strings, as #helb's answer does.)
As has already been noted, your way doesn't work because you're trying to replace a conditional statement with a conditional expression, and conditional expressions have to have a value. Since report.Load apparently returns void, a conditional expression of the form cond ? report.Load(...) : report.Load(...) doesn't have a value, ergo it doesn't work.
Each of the ways above will work because the conditional expressions in them have values - in the first case, the value will be of the type returned by Server.MapPath; in the second case, the value will be of type string.
As to whether you should do this: there are arguments to be made either way. The original way has the advantage of being clear and simple, but it does involve some (arguably undesirable) repetition. The latter approach above has the advantage of only saying things once and emphasising the intent of the whole statement (to load a report), but it's arguably slightly less clear than the original, depending on how used people are to seeing conditional expressions. YMMV.
This syntax is just for cases where it returns something. So you could do something like:
var path = (data.BaseCompareId == 2) ? "~/Content/StimulReports/MonthGroup.mrt" : "~/Content/StimulReports/YearGroup.mrt";
report.Load(Server.MapPath(path));
This is the most concise I could get for a one-liner...
report.Load(Server.MapPath(string.Format("~/Content/StimulReports/{0}Group.mrt", data.CompareId == 2 ? "Month" : "Year")));
However, it seems you just want to make things look cleaner.
More abstraction between data calls and the conditional logic.
You might want to consider making them separate methods, perhaps on your report object?
if(data.CompareId == 2)
report.LoadStimulReports(ReportGroup.Month);
else
report.LoadStimulReports(ReportGroup.Year);
Using an enum, extension method, and static method on your report object...
public enum ReportGroup
{
[DescriptionAttribute("~/Content/StimulReports/MonthGroup.mrt")]
Month,
[DescriptionAttribute("~/Content/StimulReports/YearGroup.mrt")]
Year
}
public static T GetAttribute<T>(this Enum e) where T : Attribute
{
System.Reflection.FieldInfo fi = e.GetType().GetField(e.ToString());
object[] o = (object[])fi.GetCustomAttributes(typeof(T), false);
return o.Length > 0 ? (T)o[0] : default(T);
}
public static void LoadStimulReports(ReportGroup reportGroup)
{
report.Load(Server.MapPath(reportGroup.GetAttribute<DescriptionAttribute>().Description));
}
Now you can simply add another item to the enum if you need another report.
[DescriptionAttribute("~/Content/StimulReports/WeekGroup.mrt")]
Week

What's the point of "As" keyword in C#

From the docs:
The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:
expression as type
is equivalent to:
expression is type ? (type)expression : (type) null
except that expression is evaluated only once.
So why wouldn't you choose to either do it one way or the other. Why have two systems of casting?
They aren't two system of casting. The two have similar actions but very different meanings. An "as" means "I think this object might actually be of this other type; give me null if it isn't." A cast means one of two things:
I know for sure that this object actually is of this other type. Make it so, and if I'm wrong, crash the program.
I know for sure that this object is not of this other type, but that there is a well-known way of converting the value of the current type to the desired type. (For example, casting int to short.) Make it so, and if the conversion doesn't actually work, crash the program.
See my article on the subject for more details.
https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/
Efficiency and Performance
Part of performing a cast is some integrated type-checking; so prefixing the actual cast with an explicit type-check is redundant (the type-check occurs twice). Using the as keyword ensures only one type-check will be performed. You might think "but it has to do a null check instead of a second type-check", but null-checking is very efficient and performant compared to type-checking.
if (x is SomeType )
{
SomeType y = (SomeType )x;
// Do something
}
makes 2x checks, whereas
SomeType y = x as SomeType;
if (y != null)
{
// Do something
}
makes 1x -- the null check is very cheap compared to a type-check.
Because sometimes you want things to fail if you can't cast like you expect, and other times you don't care and just want to discard a given object if it can't cast.
It's basically a faster version of a regular cast wrapped in a try block; but As is far more readable and also saves typing.
It allows fast checks without try/cast overhead, which may be needed in some cases to handle message based inheritance trees.
I use it quite a lot (get in a message, react to specific subtypes). Try/cast wouuld be significantly slower (many try/catch frames on every message going through) - and we talk of handling 200.000 messages per second here.
Let me give you real world scenarios of where you would use both.
public class Foo
{
private int m_Member;
public override bool Equals(object obj)
{
// We use 'as' because we are not certain of the type.
var that = obj as Foo;
if (that != null)
{
return this.m_Member == that.m_Member;
}
return false;
}
}
And...
public class Program
{
public static void Main()
{
var form = new Form();
form.Load += Form_Load;
Application.Run(form);
}
private static void Form_Load(object sender, EventArgs args)
{
// We use an explicit cast here because we are certain of the type
// and we want an exception to be thrown if someone attempts to use
// this method in context where sender is not a Form.
var form = (Form)sender;
}
}
I generally choose one or the other based on the semantics of the code.
For example, if you have an object that you know that it must be an string then use (string) because this expresses that the person writing the code is sure that the object is a string and if it's not than we already have bigger problems than the runtime cast exception that will be thrown.
Use as if you are not sure that the object is of a specific type but want to have logic for when it is. You could use the is operator followed by a cast, but the as operator is more efficient.
Maybe examples will help:
// Regular casting
Class1 x = new Class1();
Class2 y = (Class2)x; // Throws exception if x doesn't implement or derive from Class2
// Casting with as
Class2 y = x as Class2; // Sets y to null if it can't be casted. Does not work with int to short, for example.
if (y != null)
{
// We can use y
}
// Casting but checking before.
// Only works when boxing/unboxing or casting to base classes/interfaces
if (x is Class2)
{
y = (Class2)x; // Won't fail since we already checked it
// Use y
}
// Casting with try/catch
// Works with int to short, for example. Same as "as"
try
{
y = (Class2)x;
// Use y
}
catch (InvalidCastException ex)
{
// Failed cast
}

best way to check class

I have a method which is taking in a parameter that is a Interface object
like this
private void SomeMethod(InterfaceA IUA)
Inside the method I have a statement like this
ClassD someVar = (ClassD)(((ClassC)((ClassB)IUA)).D);
everything if fine and dandy. However, in certain cases the object IUA might be instance of ClassZ rather than ClassB. So in that case the above line errors out. Is there a way to find out, before doing above statement, that which class does the object really belong to? If i know that before hand then I can have an If statement and do the following
ClassZ someVar = (ClassD)(((ClassC)((ClassZ)IUA)).Z);
I come from java background...In java i know we have getClass() ...what would be the equivalent in .net?
You really shouldn't be writing code like this without good reason.
That said: you can use is
if (a is ClassB)
{
ClassB b = (ClassB)a;
}
else if (a is ClassZ)
{
ClassZ z = (ClassZ)a;
}
...or as:
ClassB b = a as ClassB;
if (b != null)
{
// ...
}
Well, for starters, you're not really supposed to downcast from interface to a class, unless you have a really good reason to do so. If you need ClassD functionality, then your method should receive ClassD, not InterfaceA.
Another thing that confuses me is the multiple downcasting. I use both Java and C# and I've never seen the need to do a multiple cast like that.
Finally, you could use operator "is" to find out whether certain type inherits from a certain class or implements a certain interface, as in
if (IUA is ClassD)
{
// do something
}
You can do
if (someVar is ClassZ)
Which returns TRUE if someVar is-a ClassZ,
or
someVar.GetType ()
to get the actual class
How about
if(IUA is ClassB)
someVar = (IUA as ClassB).B;
elseif (IUA is ClassZ)
someVar = (IUA as ClassZ).Z;
That should work, though you get the mandatory scolding that this is a rather poor architecture.
What is the point of passing the interface if your just going to cast it away? You might want to re-evaluate the design as code like this defeats the purpose of polymorphism.
Also you should not use 'is' to test the type. Since you are going to cast the object anyway you should use 'as' and test for null.
Okay, a few different options here:
The equivalent for Java's getClass() is GetType(); you can use typeof(...) to retrieve the Type object for a type you know at compile-time. This isn't the best way of testing things though, unless you're interested in exact equality.
The equivalent of Java's instanceof operator is the is operator in C#:
if (x is SomeType) ...
This can be used with boxed values to check for value types, too:
if (x is int) ...
A related operator is the as operator, which doesn't return true or false, but a reference of the type specified. The type has to be a nullable type (reference or nullable value type) and the result is the original value but strongly typed as the target type if the value is a reference of an appropriate type, or null otherwise. For instance:
object x = "hello";
string y = x as string; // y = "hello" now
Stream z = x as Stream; // z = null now
In the case where you want to check whether or not a reference is of a particular type, and then use it as a reference of that type, a common pattern is:
object x = GetObjectFromSomewhere();
string y = x as string;
if (y != null)
{
Console.WriteLine(y.Length); // Whatever
}
This is more efficient than the equivalent to what's required in Java:
object x = GetObjectFromSomewhere();
if (x is string)
{
string y = (string) x;
Console.WriteLine(y.Length); // Whatever
}
If it's a bug for the reference to be of the wrong type, just cast - that way you'll get an exception thrown if you've got a bug, which is almost certainly the best course of action at that point.
I don't think it's necessary to cast IUA to ClassB. You're not using any of the ClassB methods as far as I can tell.
You could do something like
If (IUA is ClassB)
//I am class b
However, given that your method is taking an interface, I would question your design if you are looking to get back to the actual concrete type. Can you re-factor to create an interface method that you can use to perform the actions of that method.
From MSDN:
public static void Test (object o)
{
Class1 a;
Class2 b;
if (o is Class1)
{
Console.WriteLine ("o is Class1");
a = (Class1)o;
// do something with a
}
else if (o is Class2)
{
Console.WriteLine ("o is Class2");
b = (Class2)o;
// do something with b
}
else
{
Console.WriteLine ("o is neither Class1 nor Class2.");
}
}
You should use method overloading, this is how it should look:
private void SomeMethod(ClassB obj) {
DoMoreStuff(obj.B);
}
private void SomeMethod(ClassZ obj) {
DoMoreStuff(obj.Z);
}
private void DoMoreStuff(int val) {
// ..
}

Categories

Resources