Results 1 to 7 of 7

Thread: [RESOLVED] Pass type as the parameter to a method

  1. #1

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,201

    Resolved [RESOLVED] Pass type as the parameter to a method

    i need to pass the Type as the parameter of the function and use it.
    the Extension method is providing a short cut to extract the cell value of the datatable.

    c# Code:
    1. /// <summary>
    2.         /// Returns data row information based on key column & keyId value
    3.         /// </summary>
    4.         /// <param name="Dt"></param>
    5.         /// <param name="IDcolumnName"></param>
    6.         /// <param name="IDvalue"></param>
    7.         /// <param name="GetColumnName"></param>
    8.         /// <returns>DataRow</returns>
    9.         public static DataRow GetCellValueByIdField(this DataTable Dt,
    10.                                                  String IDcolumnName ,
    11.                                                  Object IDvalue ,
    12.                                                  Type IDcolumnType ,
    13.                                                  String GetColumnName )
    14.                                                  
    15.         {
    16.             if (Dt == null && Dt.Rows.Count <= 0 )
    17.             {
    18.                 return null;
    19.             }
    20.  
    21.             // Here Filed<type> is to be solved
    22.             // Error @
    23.             // where OpRow.Field<IDcolumnType>(IDcolumnName).Equals(IDvalue)
    24.             // the error is Can't use the type variable , it must be explicit type instead of a variable name
    25.  
    26.  
    27.             var Dr = from OpRow in Dt.AsEnumerable()
    28.                      where OpRow.Field<IDcolumnType>(IDcolumnName).Equals(IDvalue)
    29.                      select OpRow;
    30.  
    31.             return Dr.FirstOrDefault();              
    32.            
    33.  
    34.  
    35.         }
    hoe to fix it please
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,598

    Re: Pass type as the parameter to a method

    The clue should have been in the way you're using it within the method. Field is a generic method and your are setting its generic type parameter. Your method needs to be the same. You need to understand the difference between a Type object and a data type. A Type object is an instance of the Type class that contains information about a data type. You cannot turn a Type object into a data type.
    csharp Code:
    1. public static class DataTableExtensions
    2. {
    3.     public static DataRow GetRowById<T>(
    4.         this DataTable source,
    5.         string idColumnName,
    6.         object idValue)
    7.     {
    8.         return source?.AsEnumerable().FirstOrDefault(dr => dr.Field<T>(idColumnName).Equals(idValue));
    9.     }
    10. }
    When you call that method, you fix T and that same data type is then used internally when calling Field, e.g.
    csharp Code:
    1. Dim row = table.GetRowById<int>("ThingId", 1);
    As you can also see, the code can be simplified from what you had. Using source?.AsEnumerable() instead of source.AsEnumerable() takes care of the possibility that the source reference is null, as the expression immediately evaluates to null instead of throwing a NullReferenceException. There's no need to have a separate where clause and then call FirstOrDefault because FirstOrDefault can do the filtering itself. Finally, using function syntax instead of query syntax removes the need for the from and select clauses, thus making the code even more concise. If you prefer to use query syntax all the time then by all means do so but, personally, I tend to use function syntax as a first option and only use query syntax when function syntax would be harder to read.

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,598

    Re: Pass type as the parameter to a method

    Actually, I just realised that it can be even simpler because the ID type can be inferred from the ID value you pass:
    csharp Code:
    1. public static DataRow GetRowById<T>(
    2.     this DataTable source,
    3.     string idColumnName,
    4.     T idValue)
    5. {
    6.     return source?.AsEnumerable().FirstOrDefault(dr => dr.Field<T>(idColumnName).Equals(idValue));
    7. }
    That means that you don't have to explicitly specify T and it will simply be inferred:
    csharp Code:
    1. Dim row = table.GetRowById("ThingId", 1);
    That will infer T to be int because the last argument is type int. If you do this:
    csharp Code:
    1. Dim row = table.GetRowById("ThingId", 1L);
    then T will be inferred to be long.

  4. #4

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,201

    Re: Pass type as the parameter to a method

    Thanks for the reply sir
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  5. #5

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,201

    Re: Pass type as the parameter to a method

    Sir thanks for the guidance, now i can able to fetch data directly from the DataTable
    vb.net Code:
    1. /// <summary>
    2.         /// Returns cell value in a datatable, Of a row (row identified by the unique key value of a key column)
    3.         /// </summary>
    4.         /// <param name="Dt"></param>
    5.         /// <param name="IDcolumnName">String</param>
    6.         /// <param name="IDvalue">int</param>  
    7.         /// <param name="FetchingColumnName">The column name from which we need value output</param>
    8.         /// <returns>DataRow</returns>
    9.         public static OUTPUTTYPE GetCellValueByRowKey<KEYVALUETYPE,OUTPUTTYPE>(this DataTable Dt,
    10.                                                  String IDcolumnName ,
    11.                                                  KEYVALUETYPE IDvalue ,
    12.                                                  String FetchingColumnName)
    13.                                                  
    14.         {
    15.  
    16.             // First filter the row by primary column key value of type KEYVALUETYPE
    17.             // then return the field value of column FetchingColumnName of type OUTPUTTYPE
    18.  
    19.             var OutPut = Dt.AsEnumerable().FirstOrDefault(findRow => findRow.Field<KEYVALUETYPE>(IDcolumnName).Equals(IDvalue)).Field<OUTPUTTYPE>(FetchingColumnName);          
    20.  
    21.             return OutPut;              
    22.  
    23.  
    24.         }
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

  6. #6
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,598

    Re: Pass type as the parameter to a method

    What you do is up to you but you really ought to follow the same naming convention for generic type parameters as is used throughout the Framework and by other developers the world over. That means the following:

    1. Use T by default and only use something else if there is good reason. That you have multiple generic type parameters is a good reason.
    2. If you don't use T, use a sensible name and prefix it with T.
    3. Use Pascal casing as you would for any other type.

    That means that your code should be something like this:
    Code:
            public static TResult GetCellValueByRowKey<TKey, TResult>(this DataTable Dt,
                                                     String IDcolumnName ,
                                                     TKey IDvalue ,
                                                     String FetchingColumnName)
                                                     
            {
     
                // First filter the row by primary column key value of type KEYVALUETYPE
                // then return the field value of column FetchingColumnName of type OUTPUTTYPE
     
                var OutPut = Dt.AsEnumerable().FirstOrDefault(findRow => findRow.Field<TKey>(IDcolumnName).Equals(IDvalue)).Field<TResult>(FetchingColumnName);           
     
                return OutPut;              
     
     
            }
    Also, it is VERY bad that you are calling FirstOrDefault and then calling Field directly on the result. It shows that you don't understand what FirstOrDefault does and how it differs from similar methods. The whole point of the OrDefault part is that it will return Nothing if there is no matching item. Is there the possibility of there being no match or not? If there isn't then you shouldn't be calling FirstOrDefault in the first place. If there is then your code should not be assuming that the result will not be Nothing.

  7. #7

    Thread Starter
    PowerPoster make me rain's Avatar
    Join Date
    Sep 2008
    Location
    india/Hubli
    Posts
    2,201

    Re: Pass type as the parameter to a method

    Got it sir
    1. Use T by default and only use something else if there is good reason. That you have multiple generic type parameters is a good reason.
    2. If you don't use T, use a sensible name and prefix it with T.
    3. Use Pascal casing as you would for any other type.
    The averted nuclear war
    My notes:

    PrOtect your PC. MSDN Functions .OOP LINUX forum
    .LINQ LINQ videous
    If some one helps you please rate them with out fail , forum doesn't expects any thing other than this

Posting Permissions

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



Click Here to Expand Forum to Full Width