Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Simple String Generator Source [C#]

Coded in literally 10 minutes, mainly experimenting with the '?:' operators.

Source (Added Comments):
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class StringGenerator
{
    /* global field(s) */
    private Random provider;

    public StringGenerator(int seed = -1)
    {   /* specifing a default value makes the parameter optional.
  *  if the seed is the default value (-1) we are setting our random
  *  generator seed to the current system time in milliseconds, otherwise
  *  we are setting the seed to the user inputted.
  *  The  ? : operators works like this:
  *  (condition) ? expression is true : expression is false;
  */
  provider = new Random( (seed == -1) ? DateTime.Now.Millisecond : seed );

    }

    private char newChar(bool useUpper) /* determine whether or not to use upper case letters */
    {
  return (char)((provider.Next(64, 90) + 1) + ((useUpper && provider.Next(2) == 0) ? 32 : 0));
  /*  if useUpper is true and the random value is 0 it will
  *  add 32 to make the decimal value in the upper case letter bounds.
  */
    }

    private char newNum()
    {
  return (provider.Next(10) + "").ToCharArray()[0];
  /* adding a blank string automatically casts the expression to a string.
  * converting to a char array and getting the first position is more simple
  * then doing the ASCII value of the numbers.
  */
    }

    public string Generate(int length, bool useUpperCase = true)
    {
  string output = ""; /* declare the return string */
  for (int pos = 0; pos < length; pos++) /* basic for syntax (declaration, condition, mutation) */
    output += (provider.Next(2) == 0) ? newChar(useUpperCase) : newNum();
    /* if our random value is 0 adds a new character otherwise it adds a new number. */
  return output;
    }
}

Screen Shot:

[Image: 3e179b4953425225163219ed07a2f465.png]
Very Good For Beginners Or VB.net Coders who wants to move to C# Like Me :D
Thanks for this, will help me learn more about C#.
Thanks guys! Added comments so you know exactly what I'm doing at each stage.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Python] by GREGORYNov 26, 2019 07:02 AM 2 240 Nov 26, 2019 07:02 AM
Last Post: Kallu609
[C] by MordiciaNov 15, 2019 07:21 PM 3 211 Nov 15, 2019 07:21 PM
Last Post: Mordicia
[Python] by FaberCastellNov 7, 2018 03:38 PM 11 336 Nov 7, 2018 03:38 PM
Last Post: Qismon