Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic Casting with Linq

I have a class that interfaces with a linq class and uses the System.Data.Linq.Binary datatype. I'm trying to write a simple class that takes a generic arrangement that denotes the datatype 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 StringClass.Value correctly cast and return a string from the database?

Will ByteClass.Value correctly cast and return a byte[] from the database?

My main question basically resolves around how System.Data.Linq.Binary can be used.

Edit: How do I convert System.Data.Linq.Binary to T where T can be anything. My code doesn't actually work because I can't cast Binary to T using as.

like image 644
Kris Avatar asked Jun 06 '26 12:06

Kris


1 Answers

essentially you are doing

System.Data.Linq.Binary b1;

string str = b as string;

and

System.Data.Linq.Binary b2

byte[] bArray = b2 as byte[];

both str 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;
    }
}
like image 91
Bala R Avatar answered Jun 09 '26 00:06

Bala R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!