none
DirectCast equivalent in C#

    Question

  • Hi, im creating a web browser and am working on implementing tabbed browsing however the function im used to using for accessing dynamically created objects (DirectCast();) does not work with C#. Im looking for a way to do this in C# any help would be greatly appreciated.

    Thursday, December 31, 2009 9:08 PM

Answers

  • In C#, you can use a cast to accomplish the same thing, although the is and as operators can also potentially be used.

    Say you have an object, containing a label:

    Dim obj As Object = myLabel
    Dim label as Label = DirectCast(obj, Label)
    The direct C# equivelent would be:

    object obj = myLabel;
    Label label = (Label) myLabel; // Cast to Label type
    You may also want to investigate the is and as keywords.  They let you do:

    object obj = myLabel;
    
    if (obj is Label)
    {
      // You know obj is a Label here!
    }
    
    Label label = obj as Label; // This will return null if obj is not a label, otherwise, cast it...


    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by eryang Thursday, January 14, 2010 10:18 AM
    Thursday, December 31, 2009 9:45 PM
    Moderator

All replies

  • In C#, you can use a cast to accomplish the same thing, although the is and as operators can also potentially be used.

    Say you have an object, containing a label:

    Dim obj As Object = myLabel
    Dim label as Label = DirectCast(obj, Label)
    The direct C# equivelent would be:

    object obj = myLabel;
    Label label = (Label) myLabel; // Cast to Label type
    You may also want to investigate the is and as keywords.  They let you do:

    object obj = myLabel;
    
    if (obj is Label)
    {
      // You know obj is a Label here!
    }
    
    Label label = obj as Label; // This will return null if obj is not a label, otherwise, cast it...


    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by eryang Thursday, January 14, 2010 10:18 AM
    Thursday, December 31, 2009 9:45 PM
    Moderator
  • This (I believe) is actually a CType equivalent but both will work in your situation.
    Saturday, January 02, 2010 9:05 PM
  • This (I believe) is actually a CType equivalent but both will work in your situation.

    Yes - C# casting with a type in parentheses is equivalent to both CType and DirectCast.
    Actually, using the System.Convert class methods is a closer equivalent for conversion of CType, but not DirectCast.

    The C# equivalent to VB's TryCast is to use the 'as' operator.

    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Saturday, January 02, 2010 11:06 PM