Cannot convert type 'T' to bool

Basically, I have errors like this, where the code is highlighted in bold:

Cannot convert type 'T' to bool
Cannot convert type 'T' to string x2
Cannot convert type 'T' to byte[]
Cannot convert type 'T' to byte

I searched all over google and can't find a way around this, thanks in advance

public void Append<T>(T value, bool littleEndian = false)
    {
        try
        {
            System.Type t = typeof(T);
            if (!this.IsValidType(t))
            {
                throw new Exception("msg_t.AppendMessage: Invalid type!");
            }
            if (t == typeof(bool))
            {
                ((XDevkit.IXboxConsole) this.XboxConsole).WriteInt32(this.DataBuffer + this.MessageLength, ***((bool) value)*** ? 1 : 0);
                this.MessageLength += 4;
            }
            else if (t == typeof(string))
            {
                ((XDevkit.IXboxConsole) this.XboxConsole).WriteString(this.DataBuffer + this.MessageLength, ***(string) value)***;
                this.MessageLength += (uint) Encoding.UTF8.GetBytes(***(string) value)***.Length;
            }
            else if (t == typeof(byte[]))
            {
                byte[] data = ***(byte[]) value***;
                ((XDevkit.IXboxConsole) this.XboxConsole).SetMemory(this.DataBuffer + this.MessageLength, data);
                this.MessageLength += (uint) data.Length;
            }
            else if (t == typeof(byte))
            {
                ((XDevkit.IXboxConsole) this.XboxConsole).WriteByte(this.DataBuffer + this.MessageLength, ***(byte) value***);
                this.MessageLength++;
            }
            else
            {
                byte[] array = (byte[]) typeof(BitConverter).GetMethod("GetBytes", new System.Type[] { value.GetType() }).Invoke(null, new object[] { value });
                if (!littleEndian)
                {
                    Array.Reverse(array);
                }
                ((XDevkit.IXboxConsole) this.XboxConsole).SetMemory(this.DataBuffer + this.MessageLength, array);
                this.MessageLength += (uint) array.Length;
            }
            this.UpdateOverflowedBoolean();
        }
        catch
        {
            if (MessageBox.Show("Error when writing stats!", "GHOSTS", MessageBoxButtons.RetryCancel, MessageBoxIcon.Hand) == DialogResult.Retry)
            {
                this.Append<T>(value, littleEndian);
            }
        }
    }
+4
source share
1 answer

Unfortunately, the rules for general conversions in C # do not allow this directly, but you can go through object. For instance:

byte[] data = (byte[]) (object) value;

However, you might wonder if this is really suitable for this universal method ... it does not look like all types or does the same for all types that it accepts.

I also highly recommend extracting an expression ((XDevkit.IXboxConsole) this.XboxConsole)that is used in all cases of success.

+10
source

All Articles