DEV Community

Kiron Roy
Kiron Roy

Posted on • Updated on

C# Instantiated classes, Zelda example

c sharp logo

This is is also on replit

  • Instantiated classes are a key aspect to Object Oriented programming.

  • Here is a CharacterModel. It holds data with two properties

    • FirstName which of string type
    • Role which is also string type

CharacterModel.cs

using System;
using System.Collections.Generic;

public class CharacterModel 
{


  public string FirstName {get; set;}
  public string Role {get; set;}

}
Enter fullscreen mode Exit fullscreen mode
  • List is a blueprint, instantiating (creating) a list is a type. Just like bool, double, string are types.

  • Character model is also a type. It can be used in a list:

    • List<CharacterModel> characters = new List<CharacterModel>();
    • CharacterModel character = new CharacterModel();
  • Variable holds the "street address" (memory address). NOT the actual object.

  • Building new object in a different location but still calling it character.

  • The old address is already built and stays there.

  • The new variable (with the same name as character) holds a new address and is for a brand new object (in this case a character object).

main.cs

class MainClass {
  public static void Main () 
  {

    List<CharacterModel> characters = new List<CharacterModel>();

   // Creating a instance of the object

   CharacterModel character = new CharacterModel();  


   // Zelda character created and added to characters list. 

    character = new CharacterModel();
    character.FirstName = "Zelda";
    character.Role = "Princess";
    characters.Add(character);

   // Link 

    character = new CharacterModel();
    character.FirstName = "Link";
    character.Role = "Hero";
    characters.Add(character);

   // Gannon    

    character = new CharacterModel();
    character.FirstName = "Ganon";
    character.Role = "Enenmy";
    characters.Add(character);

    // Just copying street address NOT making duplicates 

    foreach (CharacterModel c in characters)
    {
      Console.WriteLine(); // breakline
      Console.WriteLine($"{c.FirstName} is the {c.Role}" );
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
thebuzzsaw profile image
Kelly Brown

You can't get me all excited about Zelda content and then misspell Ganon.

Collapse
kironroy profile image
Kiron Roy Author

Thanks Kelly! Fixed Gannon to Ganon*