0

I was wondering how can I declare a string variable with my name adding my birth month as a number on it. IF I CAN. I'm not coding so I only have to know if I can do it or not, but if it is possible show me how.

  • Most likely you can do it only if you're using something like `Reflection.Emit`... But why do you want to achieve that ? – Fabjan Feb 16 '19 at 11:36
  • 2
    Possible duplicate of [Create dynamic variable name](https://stackoverflow.com/questions/20857773/create-dynamic-variable-name) – Dineth Cooray Feb 16 '19 at 11:38
  • you want something like `$"{myName}{birthMonth}"` or what? – Ondřej Kubíček Feb 16 '19 at 11:38
  • @Fabjan - it was a question in on of my exams before. So I'm being ready if accidentally my profesor will post it the same question. So I haave to know if it is possible for a begginer, it is a provocative question. –  Feb 16 '19 at 11:45
  • @Joooohn Well, C# is a strongly typed language so unless you're using some hacks - you can't – Fabjan Feb 16 '19 at 12:09
  • You have to clarify exactly what you mean. Most of the comments and answers are probably way over-thinking it. I suspect your teacher was looking for something very simple like `string nameMonth = "Jooooon" + birthMonth.ToString();` – Crowcoder Feb 16 '19 at 12:09

2 Answers2

0

If this items are in a class, you could do ToString() method like this:

public override ToString()
{
   return string.Format("{0}, {1}", this.Name, this.BirthdayMonth);
}

then when you do a Writeline for example you can do

Console.WriteLine(person.ToString());
0

You can declare a Person class that encapsulates a person's last name, first name and birthday.

public class Person 
{

  public DateTime BirthDay {get;}
  public string LastName {get;}
  public string FirstName {get;}

  public Person(string lastName,  string firstName, DateTime birthDay) => (LastName, FirstName, BirthDay) = (lastName, firstName, birthDay);

  public override string ToString() => $"{FirstName} {LastName} {BirthDay.Month}";
}

And call ToString to get the result that you want.

Zack ISSOIR
  • 964
  • 11
  • 24