Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In mobile phones technologies, a SectorId is a 128-bit value broadcast by a 1xEV-DO BTS system.

That is a 16 bytes data.

I made a structure to store them:

using System;
using System.Globalization;
using System.Linq;
using System.Text;

public struct SectorId
{
    readonly byte[] id;

    SectorId(byte[] id)
    {
        this.id = new byte[16];
        Array.Copy(id, this.id, 16);
    }

    public override bool Equals(object obj)
    {
        if (obj is SectorId)
        {
            return Equals((SectorId)obj);
        }

        return false;
    }

    public bool Equals(SectorId other)
    {
        return id.SequenceEqual(other.id);
    }

    public override int GetHashCode()
    {
        int hash = 0;
        unchecked
        {
            foreach (var b in id)
            {
                hash *= 397;
                hash += b;
            }
        }
        return hash;
    }

    public static SectorId Parse(string s)
    {
        Throw.IfArgumentIsNull("s", s);

        SectorId result;
        if (TryParse(s, out result))
        {
            return result;
        }

        throw new FormatException();
    }

    public override string ToString()
    {
        var sb = new StringBuilder();
        foreach (var b in id)
        {
            sb.AppendFormat("{0:X2}", b);
        }
        return sb.ToString();
    }

    public static bool TryParse(string s, out SectorId result)
    {
        if (s == null)
        {
            goto Fail;
        }

        if (s.Length > 32)
        {
            goto Fail;
        }

        if (s.Length < 32)
        {
            s = s.PadRight(32, '0');    
        }

        var bytes = new byte[16];

        for (var i = 0; i < 16; i++)
        {
            var substring = s.Substring(i * 2, 2);
            if (!byte.TryParse(substring, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out bytes[i]))
            {
                goto Fail;
            }
        }

        result = new SectorId(bytes);
        return true;

        Fail:
        result = default(SectorId);
        return false;
    }
}

The TryParse part is the worse for me. I would like to avoid gotos.

share|improve this question

Note that you can use multiple return statements in a method, so instead of using goto, you can use a return statement. I.e:

if (s == null)
{
    return false;
}
share|improve this answer
2  
Don't forget to initialise the out parameter first. – RobH Feb 19 at 10:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.