0

Can I create int.FromBytes(byte[] bytes) extension method in C#?

I need something with usage like this:

int a = int.FromBytes(new byte[]{1,2,3,4});

I'm using C# 7.3.


Actually I need this for ushort data type. For now I'm using extension method like this:

public static ushort FromBytes(sbyte msb, byte lsb)
{
    ushort usmsb = (byte)msb;
    ushort uslsb = lsb;

    return (ushort)((usmsb << 8) + uslsb);
}

I'm using it like this:

ushort x = Helpers.FromBytes(1, 2);

I can't answer my closed question, so I post it here. This is how I did it and what I needed:

// two byte tuple extension
public static ushort ToUShort(this (byte msb, byte lsb) bytes)
{
    ushort usmsb = bytes.msb;
    ushort uslsb = bytes.lsb;
    return (ushort)((usmsb << 8) + uslsb);
}

Usage:

byte byte1 = 32;
byte byte2 = 42;
ushort result = (byte1, byte2).ToUShort();

This is much better than extension for byte[] because you can't pass wrong number of bytes.

Kamil
  • 13,363
  • 24
  • 88
  • 183
  • What happened when you tried? – Scott Hunter Jul 05 '19 at 17:12
  • 2
    You don't need to, it's already [there](https://learn.microsoft.com/de-de/dotnet/api/system.bitconverter.toint32?view=netframework-4.8) – René Vogt Jul 05 '19 at 17:12
  • 1
    That FromBytes method is (as shown) a static method on int. You can't currently write static extension methods. You could write an extension method on byte arrays (or even `IEnumerable`. Something like `new byte[] {1, 2, 3, 4}.ToInt()`) – Flydog57 Jul 05 '19 at 17:18
  • Your FromBytes() is not an extension method. It's just a static method. – Han Jul 05 '19 at 17:21
  • @ScottHunter Nothing happened. I don't know the syntax to create extension like this. – Kamil Jul 05 '19 at 17:21
  • @Han RIght. I have extension method to convert it back. I messed up my question. – Kamil Jul 05 '19 at 17:23
  • @RenéVogt I know about BitConverter, byt my question is about language. – Kamil Jul 05 '19 at 17:24
  • @Flydog57 This is exactly what I want, I have this for conversion back, but I didn't thought about this this obvious way :) Can you post this as an answer? – Kamil Jul 05 '19 at 17:27
  • You should really read the duplicate question before stating that your question isn't a duplicate, given that it's asking for exactly what you claim to be asking, and gives you exactly the answer you claim you want. – Servy Jul 05 '19 at 17:52

1 Answers1

0

Yes, you can map to the existing static method with your own static extension method, if you think it is worth the trouble.

static public class ExtensionMethods
{
    static public int ToInt32(this byte[] source)
    {
        return BitConverter.ToInt32(source, 0);
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80