C# "as" operator and advanced conversion use in loops/functions and out/ref parameters modifiers and typeof() [duplicate]

StackOverflow https://stackoverflow.com/questions/17712217

  •  03-06-2022
  •  | 
  •  

Pregunta

I Need some clarifications about:

is/as operators

out/ref parameters modifiers

typeof

Feel free to reply only to what you know or what you want to reply and not the whole question if you don't feel like.

Yes, I'm asking clarifications about these. Correct me or add to what I've already said.

Well, I've googled a bit and landed up on various sites, MSDN and so on. I still need someone to write up some code to help me clarify the whole concept and finally let me use it in its full power, hoping that this will be helpful for others too.

Basically this is what I've understood:

A) is

In pseudocode

If object is this type return true, else false

Easy. Or I am doing something wrong here?

Are there any limitations or problems with some types?

This code runs fine, so I guess I got this good.

object s = new SqlBoolean();
        if (s is SqlBoolean)
        {
            Console.WriteLine("Is SqlBoolean");
            Console.ReadLine();
        }

2) as

Well, I still have to fully understand this.

MSDN Reports:

The as operator is used to perform conversions between compatible types. The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.

Well I tried a loop on an Object array and it basically converts only primitives and with lot of problems (every casting more than a little difficult throws null or something)

I.e

using System;
using System.Data.SqlTypes;

class StackOverflow
{
    public static void Main()
    {
        string country = "jii";
        string vatNum= "dde";

        object[] MyObjects = {country,
                              vatNum
                             };

        for (int i = 0; i<=MyObjects.Length-1;i++)
        {
            MyObjects[i] = MyObjects[i] as SqlString?;
            Console.WriteLine(MyObjects[i].ToString() + " " + MyObjects[i].GetType());
            Console.ReadLine();
        }
    }
} 

In a program I am making I need those values to be converted into SqlStrings, SqlBooleans and so on.

Pay attention at the fact that I'm forcing SqlString to Nullable with the line "SqlString?" with the question mark at the end (? forces to nullable, who knew it! :D).

So basically it's useful for doing some low level conversion without using exceptions? Or what?

3) ref and out

Well basically ref changes the value of a predeclared variable from within a function:

IE

using System;

class StackOverflow
{
    public static void Main()
    {
        int x = 10;
        Write(func(ref x).ToString());
        Write(Convert.ToString(x));
    }

    public static int func(ref int y)
    {
        y += 10;
        return y;
    }

    public static void Write(string z)
    {

        Console.WriteLine(z);
        Console.ReadLine();

    }
} 

Executing this will be ok and output will be 20 20 removing both ref will output 20 10

(ref changes the externally declared x directly without making an instance in the method)

What about out? What's the use????

I can't get it. Reading somewhere it seems it's like a parameter that does the same of ref, but it lets you somehow have some output parameter.

Putting out instead of ref in the previously shown code will only produce compilation errors by IntelliSense and I don't even know how to get those out parameters to show.

In a project I'm doing I'm using the following code:

public static Array check(string country, string vatNum)
{
    bool valid;
    string name;
    string address;
    checkVatService vatchecker = new checkVatService();
    vatchecker.checkVat(ref country, ref vatNum, out valid, out name, out address);

    return new object[] {country,
                         vatNum,
                         valid,
                         name,
                         address
                         };
}

Now, checkVat is some code from the european online checking webservice.

I see it has out parameters and they are generated by the wsdl webservice consuming library from the webservice website (link to library, if needed)

How do I use the out parameters? Are them something to have some output without using return? How I use them? Please be very detailed

4) typeof

This returns the type from System.Type of the Type you pass to it.

First I thought I could get the type of any object I passed to it like

int x;
SqlBoolean xy = new SqlBoolean();
typeof(x) // integer
typeof(xy) // SqlBoolean

but it's not that.

It just returns the type from System.Type.

Like

typeof(int).ToString() // System.Int32 or something like that typeof(xy).ToString() // System.Data.SqlTypes.SqlSqlBoolean

and I don't really know what to do with that.

For getting the type of an object you gotta do something like .GetType from an object or so.

So what's the pratical use of typeof and what am I missing about it?

Thanks anyone

¿Fue útil?

Solución 5

Here's the real answer after I got the concept of out and ref myself.

Ref -> you pass a param as ref when you have previously initialized a variable outside of the method you call and you want that method to assign a result value to it.

Out -> you pass a param as output when a variable outside the method you call may be or may not be assigned and you want the method to assing it the result value

As-> Does a cast without throwing exceptions.

Also, this

Otros consejos

Large question.. small answer:

  1. Correct.
  2. It allows casts to fail without an exception. Therefore, you can check if the result is null. If it is, the cast failed.
  3. ref passes objects by reference (note: still pass-by-value semantics though!). out means a variable must be assigned to before the function exits.
  4. I'm not sure I understand your issue with typeof. It might be best to disregard its use if you don't understand why it might be useful (as with anything, really).

1) you are correct regarding the is operator
2) The use of the as operator is that it suppresses the exception of wrong case so that when a cast is wrong it throws null.
3)For ref please refer the link below, detailed explanation is given here Why use the 'ref' keyword when passing an object?
4) The out parameter is generally used in cases when you need to return more than one value from a function. One value is directly returned using the return statement and the other values are return using the out parameter. For example and clear understanding refer what is use of out parameter in c#. You can find excellent article by jon skeet in there.
5) There may arise situations where you want to check the type of an object to perform ceratain operations, but mostly this shouldn't be used according to the RTTI design principle

typeof, GetType, is are all different and can output different result. Refer to this SO post as there exists the simplest explanation I've seen.


ref and out

By default, method's arguments are passed by value, which means the value of the argument is copied when passed to a method. If you have foo(int y){y = 9;} main(){int x = 5; Foo(x);}, method Foo copies the value of x to y, then assigns y a different value. x still remains as 5. If you have reference-type argument, such as Foo(object y){y = null;} main(){object x = new object(); Foo(x);}, y contains a copied value of x, which is a reference value and not the object itself. Hence, changes made to y also do not reflect in x. In contrast, ref and out are passed by reference:

// Example of ref:
// p DOES NOT copy x's reference value of the object
// p is x (or refer to the same memory as x)

class Ref_Example
{
   static void Foo(ref int p) { p = 8};
   static void Main() { 
      int x = 5; Foo(ref x);
      Console.WriteLine(x);    // output: 8 
   }
}

// Example of out:
// out = ref, except variables need not be assigned before method is called
// You use out when you have to return multiple values from a function  
Class Out_Example
{
   static void Find_Synonyms(
          string vocab, out string synonymA, out string synonymB)
   { // Lookup the synonyms of the word "rich" };

   static void Main()
   {
      string a, b;
      Find_Synonyms("rich", a, b);
      Console.WriteLine(a);   // abundant
      Console.WriteLine(b);   // affluent
}

Of course you can break what ref/out are designed for, and use ref in place of out by assigning the variables an initial value, but it makes no logical sense and may confuses the code reader. (i.e. how would you know the synonyms before you done searching for them? and why would you assigned it an incorrect initial value? etc.)



further note:

int = System.Int32 and SqlBoolean = System.Data.SqlTypes.SqlBoolean. int is just an alias probably due to tradition, while System.Int32 is the full representation/name of the C# type. What expose int x to methods like x.Equals, x.ToString or x.Parse? System.Int32. In C#, types are classes (e.g. System.Int32) with members that define a data or reference type.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top