Looking for help learning a specific C# aspect, objects as parameters.

I’m learning C# and I’m having a tough time comprehending how to use objects and classes as parameters. Elsewhere I’ve seen confusing use of declaring variables, and in some lessons about interfaces.

For example, in this snippet I code I found, I don’t really understand what’s going on with “MyClass myClass

Source: Software Café: Confusion when Passing Reference Type Objects in C#

 private static void MyMethod(MyClass myClass) {}

I can’t seem to figure out what to search for to learn more about this. Now I’ve looked so much I think I’m even more lost than when I started. It seems many newb-sided tutorials never mention anything like this. Then other lessons assume you must already know how to do something like that.

I will give an example that shows how to pass an object in a parameter by reference - and show how not passing the reference can cause an unexpected error:

    void setStringByRef(ref string s)
    {
        s = "Hello";        //Will actually change the string object    passed into s
    }

    void setString(string s)
    {
        s = "Hello";   //creates a temp variable s, sets it to Hello, but doesn't change the original string object passed through s
    }

    string a="a",b="b";

    void Start ()
    {
        setString(a);                     //Won't change a
        setStringByRef (ref b); //Will change b

        Debug.Log (a); //A is still 'a'
        Debug.Log (b); //B is now 'hello'
    }

And just to throw in a Unity-specific example:

    void changeGameObjectByRef( ref GameObject gobj, Color newColor )
    {
        gobj.renderer.material.color = newColor;
    }

This function is useless since you can change the color if you have the original GameObject variable, but the idea behind it is what matters - that when you pass an object through a parameter that needs to be changed somehow in the function, pass it by reference so the original object actually gets changed, and not a temp one.

That’s cool but I don’t see how that relates to my question :-\

Whoever wrote that code (OP) has a class called MyClass, and every class is a type. A parameter needs a type and a name, and the propensity of programmers to use the camel case version of the type as the name is surely confusing to beginners. Think of it as

private static void MyMethod(MyClass x){}

where x is the name of the parameter and MyClass is the type.

It is based on exactly what you asked… objects as parameters.

When you pass an object as a parameter you generally just need to add ref before to make it a reference to the object. The reference means it’ll actually access the original object you put when you call the function. If you don’t use ref and pass the object as a parameter, it’ll only modify a temporary variable and not the object you intended it to.

Okay. But what happens when you pass a class you’ve made as an argument? I understand what you’re saying, but I don’t understand how to use or what to use it for.

Can you give me like a super simple example of how you would use this technique in writing something?

I gave you 3. 2 use ref objects. When passing objects you most often need to use ref especially if you’re changing the class in the function.
String is a class too. It is applied the same way in my functions as another class you made would be.

Just about everything in C# is a class (or something similar). Any method that takes a string ass a parameter is taking an instance of the string class. Maybe it is used to compare with some other string value. Maybe it is the name of a prefab to be instantiated. All these things are using the argument to do something with. Check out my signature for some tutorials on programming in C#. Not in Unity, but they do teach basic concepts.

Here is a simple example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public enum CardValue
{
    Ace,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King
}

public class PlayingCard
{
    private string suit;
    private CardValue cardValue;

    public string Suit
    {
        get { return suit; }
    }
    public CardValue CardValue
    {
        get { return cardValue; }
    }

    public PlayingCard(string suit, CardValue cardValue)
    {
        this.suit = suit;
        this.cardValue = cardValue;
    }
}

public class DeckOfCards
{
    private List<PlayingCard> cards;

    public int NumberOfCards
    {
        get { return cards.Count; }
    }

    public DeckOfCards(int maxNumberOfCards)
    {
        cards = new List<PlayingCard>(maxNumberOfCards);
    }

    public void AddCardToDeck(PlayingCard cardToAdd)
    {
        cards.Add(cardToAdd);
        Console.WriteLine("Card was Added to the Deck!");
    }
    public PlayingCard GetTopCard()
    {
        return cards[0];
    }
}

namespace ConsoleTestBed
{
    class Program
    {
        static void Main(string[] args)
        {
            PlayingCard card = new PlayingCard("Spades", CardValue.Ace);
            DeckOfCards deck = new DeckOfCards(52);

            Console.WriteLine("Number of Cards in Deck : " + deck.NumberOfCards.ToString());

            deck.AddCardToDeck(card);

            Console.WriteLine("Number of Cards in Deck : " + deck.NumberOfCards.ToString());

            PlayingCard topCardOfDeck = deck.GetTopCard();

            Console.WriteLine("Top Card Suit : " + topCardOfDeck.Suit);
            Console.WriteLine("Top Card Value : " + topCardOfDeck.CardValue.ToString());
        }
    }
}

Hope this helps!

Thanks, LiberLogic969.

That’s a lot to go over for me. I will try to break down what’s happening. I think I have to review some stuff too like LIST.

Breaking down the OP code

private static - These are both modifiers. They change the behaviour of the method.

void - This is the return type. At some point the method must give the calling code a return value of this type. void is a special type that means there will be no return value.

MyMethod - The name of the method. This will be how the method is accessed from other areas of your script.

() - Anything inside the brackets is parameters to your method. You can have multiple parameters separated by commas.

MyClass - This is the type of the parameter. The method is expecting a parameter of the type MyClass. You can use any defined type here. It could be the name of your class. It could be a class from UnityEngine, such as Vector3. It can also be a primitive, such as int or bool.

myClass - This is a name for your parameter. The name serves two purposes. Most importantly it gives you something to refer to the variable by inside the method. Second, but still important, it also forms part of the code hint when you call this method, so make it useful. speedToMoveAt is better then float1

{} - This is the method body. The code that actually runs. In here you can refer to the paramaters defined above.

It may also help to know the conventions. UpperCase names typically refer to the type of class, or a Method. camelCase names typically refer to an instance of the type.

You should also read about reference types versus value types. You won’t understand it now, but it will be important to understand later.

Another cool concept to search is method overloading.

Thanks for the help. I think I get how to use this now.

dumb example I did:

using UnityEngine;
using System.Collections;

public class Orc
{
    public string Name;
    public bool Idiot;

   

}
public class Village
{
    public string Name = "Okven";

   
    public void CheckIdiot(Orc citizen)
    {

        if (citizen.Idiot == true)
        {
            Debug.Log("The scout orc said, " + citizen.Name + ", you are an idiot. You are not welcome in " + Name + "!");
        }
        else
        {
            Debug.Log("Welcome to Okven! Not that my example should see this text anyways.");
        }
    }
}

public class Something : MonoBehaviour {

    // Use this for initialization
    void Start () {

        Village Okven = new Village();
        Debug.Log("There once was a orc village named " + Okven.Name + ".");
       
        Orc Ruktar = new Orc();
        Ruktar.Name = "Ruktar";
        Ruktar.Idiot = true;
       
        Debug.Log("And one day, an old face showed up at the gate.");
        Okven.CheckIdiot(Ruktar);
       


    }
   
    // Update is called once per frame
    void Update () {
   
    }
}
1 Like

Lol, best example ever.

I imagined it being spoken by the Skyrim elf bard and orc voice actors. ha

1 Like