SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Apr 2006
    Posts
    375
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Type Cast Query in Generic

    Code:
    private void Test<T>(ref T stVal, T endVal) 
        {
            do
            {
                stVal++;            
    
            } while (stVal < endVal);
    
        }
    I am using the above code And getting Error.
    I may easily use the code
    Test(ref int stVal, int endVal)
    But if I want to send different datatypes like int,long etc, then I have to use Generic. And I have noticed that the type conversion in this way
    [
    (T)Convert.ChangeType(stVal , typeof(T));
    ] is not working here.
    What should I do ?

  2. #2
    ALT.NET - because we need it silver trophybronze trophy dhtmlgod's Avatar
    Join Date
    Jul 2001
    Location
    Scotland
    Posts
    4,836
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ref usuage is actually discouraged and Microsoft recommends reviewing why you end up in a position where you need to use the ref keyword.

    What exactly are you trying to do?

  3. #3
    SitePoint Guru pufa's Avatar
    Join Date
    Oct 2004
    Location
    Portugal, Lisboa
    Posts
    947
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The problem with your code is that your generic constrain is too broad (you don't have any ).

    In short for your code to compile you would need to constrain T so that the operators ++ and < would be available on all possible Types of T and there is no base Type or interface that abstracts ++ or < on numeric types that you could use as a constrain on T.

    private void Test<T>(ref T stVal, T endVal) where T : SomeBaseType

    So you are left to duplicate the algorithm.

    I also agree with dhtmlgold on the ref modifier usage.
    Numeric types are immutable in C# (ValueType or structs) and usage of ref implies boxing of value types if I'm not mistaken.

    Code:
    private int Test(int stVal, int endVal) 
        {
            do
            {
                stVal++;            
                // I supose you want to do something here... :)
    
            } while (stVal < endVal);
            return stVal;
        }
    
    var x = Test(5, 10);
    Ciao, Rui...

  4. #4
    SitePoint Addict
    Join Date
    Apr 2006
    Posts
    375
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your response.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •