2

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();
 }
 }
asked Oct 30, 2012 at 19:50
1

3 Answers 3

7

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.

answered Oct 30, 2012 at 19:53
6
  • hmm what is that "@" that is being added in second version to the group variable? it is now @group Commented Oct 30, 2012 at 20:35
  • @BDotA - Looks like a typo to me. Commented 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. Like var @class, for instance. Commented Oct 30, 2012 at 20:41
  • 1
    The usage of @ is called a verbatim identifier. stackoverflow.com/questions/11851540/… Commented Oct 30, 2012 at 20:47
  • 1
    FxCop will actually warn against casting twice in the first one Commented Oct 30, 2012 at 21:30
1

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.

answered Oct 30, 2012 at 19:57
1

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.

answered Oct 30, 2012 at 23:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.