Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : 'is' keyword and checking for Not

This is a silly question, but you can use this code to check if something is a particular type...

if (child is IContainer) { //.... 

Is there a more elegant way to check for the "NOT" instance?

if (!(child is IContainer)) { //A little ugly... silly, yes I know...  //these don't work :) if (child !is IContainer) { if (child isnt IContainer) {  if (child aint IContainer) {  if (child isnotafreaking IContainer) {  

Yes, yes... silly question....

Because there is some question on what the code looks like, it's just a simple return at the start of a method.

public void Update(DocumentPart part) {     part.Update();     if (!(DocumentPart is IContainer)) { return; }     foreach(DocumentPart child in ((IContainer)part).Children) {        //...etc... 
like image 736
hugoware Avatar asked May 01 '09 14:05

hugoware


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


2 Answers

if(!(child is IContainer)) 

is the only operator to go (there's no IsNot operator).

You can build an extension method that does it:

public static bool IsA<T>(this object obj) {     return obj is T; } 

and then use it to:

if (!child.IsA<IContainer>()) 

And you could follow on your theme:

public static bool IsNotAFreaking<T>(this object obj) {     return !(obj is T); }  if (child.IsNotAFreaking<IContainer>()) { // ... 

Update (considering the OP's code snippet):

Since you're actually casting the value afterward, you could just use as instead:

public void Update(DocumentPart part) {     part.Update();     IContainer containerPart = part as IContainer;     if(containerPart == null) return;     foreach(DocumentPart child in containerPart.Children) { // omit the cast.        //...etc... 
like image 93
mmx Avatar answered Oct 27 '22 02:10

mmx


You can do it this way:

object a = new StreamWriter("c:\\temp\\test.txt");  if (a is TextReader == false) {    Console.WriteLine("failed"); } 
like image 20
cjk Avatar answered Oct 27 '22 03:10

cjk