In C#.NET language: This style of coding is recommended or the one below it?
if (sheet.Models.Data is GroupDataModel)
{
GroupDataModel gdm = (GroupDataModel)sheet.Models.Data;
Group group = gdm.GetGroup(sheet.ActiveCell.Row.Index);
if (group!=null && controller != null)
{
controller.CheckApplicationState();
}
}
or this one:
var gdm = sheet.Models.Data as GroupDataModel;
if (gdm != null)
{
Group group = gdm.GetGroup(sheet.ActiveCell.Row.Index);
if (@group!=null && controller != null)
{
controller.CheckApplicationState();
}
}
-
Relevant: stackoverflow.com/q/132445/102937Robert Harvey– Robert Harvey2012年10月30日 19:56:24 +00:00Commented Oct 30, 2012 at 19:56
3 Answers 3
If you intend to cast (or use as
) if the result of calling is
is true
, you should just call as
and avoid two cast attempts.
I prefer the second version for this reason.
-
hmm what is that "@" that is being added in second version to the group variable? it is now @groupBlake– Blake2012年10月30日 20:35:19 +00:00Commented Oct 30, 2012 at 20:35
-
@BDotA - Looks like a typo to me.Oded– Oded2012年10月30日 20:36:31 +00:00Commented Oct 30, 2012 at 20:36
-
3@BDotA - The
@
before a variable name is ignored - it allows you to use reserved keywords as variable names. Likevar @class
, for instance.Oded– Oded2012年10月30日 20:41:02 +00:00Commented Oct 30, 2012 at 20:41 -
1The usage of
@
is called a verbatim identifier. stackoverflow.com/questions/11851540/…David Anderson– David Anderson2012年10月30日 20:47:36 +00:00Commented Oct 30, 2012 at 20:47 -
1FxCop will actually warn against casting twice in the first onejk.– jk.2012年10月30日 21:30:21 +00:00Commented Oct 30, 2012 at 21:30
In short, if you already know what type it can cast to use a C-style cast:
var o = (string) iKnowThisIsAString;
Note that only with a C-style cast can you perform explicit type coercion. If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:
var txt = o as string;
if (txt != null) return txt.Replace("_","-");
//or for early return:
if (txt == null) return;
Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.
Fundamentally, they are two different things. But what do you think reads better?
if (sheet.Models.Data is GroupDataModel)
or
var gdm = sheet.Models.Data as GroupDataModel;
if (gdm != null)
You've got your answer here. Oded made a very valid point, but programming isn't much different from writing articles. It needs to be easily readable by other engineers.