Sunday, March 2, 2014

When should we use static members in a non-static class ?

at el-shitlony



In one of my projects I needed a static table of characters to create a random string so I made a class that looks like this.



public class RandomString
{
private static readonly char[] _charTable;

static RandomString()
{
_charTable = CreateCharTable();
}

public RandomString(int min, int max)
{
// ...
}

public RandomString(int length = 8)
: this(length, length)
{
}

public override string ToString()
{
StringBuilder output = new StringBuilder();

// The actual implementation.

return output.ToString();
}

private static char[] CreateCharTable()
{
IList<char> charTable = new List<char>();

for (char n = '0'; n <= '9'; n++)
{
charTable.Add(n);
}

for (char u = 'A', l = 'a'; u <= 'Z'; l++, u++)
{
charTable.Add(u);
charTable.Add(l);
}

return charTable.ToArray();
}
}

As you can see, I can have many instances of RandomString but I only need one table of characters to generate it.


P.S. I could actually hard code the string and have the same result because strings are interned in .NET so I could actually avoid having this function but I prefer it for a different reason.









at el-shitlony


What the hell is this whole shitlony post?...


Don't you have a minimum decent brain?


See, how simple your stupid code can be:



public class RandomString
{
private static readonly char[] _charTable = Enumerable // I'm using char[] just because you do it.
.Range(65, 5)
.Union(Enumerable.Range(97, 5))
.Aggregate("", (a, s) => a + (char)s)
.ToCharArray(); // use StringBuilder, if you wish...

public override string ToString() // show _charTable as string.
{
return _charTable.Aggregate("", (a, s) => a + (char)s);
}
public string ToString(int k) // get k randomic chars from _charTable.
{
Random r = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++)
sb.Append(_charTable[r.Next(_charTable.Count())]);
return sb.ToString();
}
}



Don't you a minimum decent brain?


Probably, your brain is full of synaptic connections polluted by fecal coliforms...


You can test the code above as simple as this:



RandomString rs = new RandomString();
Console.WriteLine("The whole string:\n\t{0}",rs);
Console.WriteLine("A string with 30 randomic characters:\n\t{0}", rs.ToString(30));



How can an idiot and stupid ignorant like you be made moderator, if you post replies as bad as this one?





In the beginning, there was nothing. Then the Big Bang! Now, look at me... I&#39;m ritehere.


No comments:

Post a Comment