We help IT Professionals succeed at work.
Get Started

Converting a piece of code from VB to C#

107 Views
Last Modified: 2015-06-11
A Year or so I wrote a piece of code in VB to allow me to have an array of objects that could be tested to sse if they existed i.e. not null.  I am trying to convert this to C#.  I have got the conversion this far.

    public class DataServices
    {
        public static T? Coalesce<T>(T Obj, params T[] Args)      
        {
            if (Obj != null && IsDBNull(Obj))
            {
                return Obj;
            }
            else 
            {
                foreach (T arg in Args )
                {
                    if (arg != null && IsDBNull(arg)) return arg; 
                }
            }
            return null;
         }

        public static Boolean IsDBNull(Object Value)
        {
            return DBNull.Value.Equals(Value);  
        }
    }

Open in new window


The original looked like this.

 Public Shared Function Coalesce(Of T)(ByVal obj As T, ByVal ParamArray Args() As T) As T

        If obj IsNot Nothing AndAlso Not IsDBNull(obj) Then
            Return obj
        End If

        For Each arg As T In Args
            If arg IsNot Nothing AndAlso Not IsDBNull(obj) Then
                Return arg
            End If
        Next

        Return Nothing
    End Function

Open in new window


The error I am getting is
Error      1      The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'      C:\Users\carl.symington\Documents\Visual Studio 2012\Projects\DataServices\DataServices\DataServices.cs      11      26      DataServices

I suspect it is to do with where I have tried to put T? making T a nullable object.
Comment
Watch Question
Senior .Net Consultant
CERTIFIED EXPERT
Top Expert 2016
Commented:
This problem has been solved!
Unlock 1 Answer and 9 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE