AndrewToasterr
AndrewToasterr

Reputation: 479

C# - Simplify ValueType cast

So i have question, is there any way to simplify this cast ?

(TabControl.SelectedTab.Tag as (CodeFile codeFile, TreeNode node)?).Value

The ValueType is gonna always have a value, so is there a way to get rid of the .Value ?

Upvotes: 0

Views: 105

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37440

First: this is bad code, because in case of unsuccessfull cast, as returns null, so in such case you will get NullReferenceException.

Second: you cast to a Tuple, this type doesn't have property named Value

Third: ? operator should be used right before dot: ...?.Value

To answer your question: in order to access any property on a object, we need to "ask for it" by writing its name, so no, you can't omit Value here if you want to access it.

So, your code should look like this:

(TabControl.SelectedTab.Tag as (CodeFile codeFile, TreeNode node))?.Item1 // or it could be Item2

Upvotes: 1

Watachiaieto
Watachiaieto

Reputation: 422

before as, there was this "null" pattern that was always used.

if ({thing is a thingy}) {
    thingy newThing = (thingy)thing;
    /*Code stuff here*/
}

the problem was that people found that sometimes inbetween casting the type could change etc etc...

So they gave the "as" operator - which does a cast and returns the variable as a thingy immediatly, or a null otherwise and a it prevents the null pointer problem.

You don't actually need the as operator in this case if you know that the type is certain and that the object won't be null. if That is the case, just do the regular cast pattern.

(object)TabControl.SelectedTab.Tag

(I am not certain if this is right - since I have never seen an object casted to something that almost looks like a function :P

(CodeFile codeFile, TreeNode node) result = (CodeFile codeFile, TreeNode node)TabControl.SelectedTab.Tag

Upvotes: 1

Related Questions