C # Generic Casting with Linq

I have a class that interacts with the linq class and uses the System.Data.Linq.Binary data type. I am trying to write a simple class that accepts a general schema that denotes a data type stored as binary:

// .Value is a System.Data.Linq.Binary DataType
public class DataType<T> where T : class
{
     public T Value
     {
        get
        {
            return from d in Database
                   where d.Value = [Some Argument Passed]
                   select d.Value as T;
        }
     }
}

public class StringClass : DataType<string>
{
}

public class ByteClass : DataType<byte[]>
{
}

Will it StringClass.Valuecorrectly display and return stringfrom the database?

Will it ByteClass.Valuecorrectly display and return byte[]from the database?

My main question basically decides how to use System.Data.Linq.Binary.

Edit: How to convert System.Data.Linq.Binary to T, where T can be anything. My code actually doesn't work, because I cannot use Binary to T with as.

+3
source share
1 answer

basically you do

System.Data.Linq.Binary b1;

string str = b as string;

and

System.Data.Linq.Binary b2

byte[] bArray = b2 as byte[];

both strings and bArray will be null;

you will need something like

public class DataType<T> where T : class
{
    public T Value
    {
        get
        {
           // call ConvertFromBytes with linqBinary.ToArray()
           // not sure about the following; you might have to tweak it.
            return ConvertFromBytes((from d in Database
                   where d.Value = [Some Argument Passed]
                   select d.Value).
            First().ToArray());
        }
    }

    protected virtual T ConvertFromBytes(byte[] getBytes)
    {
        throw new NotImplementedException();
    }
}

public class StringClass : DataType<string>
{
    protected override string ConvertFromBytes(byte[] getBytes)
    {
        return Encoding.UTF8.GetString(getBytes);
    }    
}

public class ByteClass : DataType<byte[]>
{
    protected override byte[] ConvertFromBytes(byte[] getBytes)
    {
        return getBytes;
    }
}
+1
source

All Articles