Convert ref class to ref object - C#

Shervan360 1,541 Reputation points
2022-10-21T22:32:31.593+00:00

Hello,

Could you please explain why I have this error? Why does conversion not allowed? Person class inherits from System.Object

Error CS1503 Argument 1: cannot convert from 'ref ConsoleApp3.Person' to 'ref object'

using System.Collections;  
  
namespace ConsoleApp3  
{  
    class Person  
    {  
        public int _age { get; private set; }  
        public Person(int age) => _age = age;  
    }  
    internal class Program  
    {  
        static void Main(string[] args)  
        {  
            Person P1 = new(10);  
            Person P2 = new(20);  
  
            Swap(ref P1,ref P2);  
  
            Console.WriteLine($"{P1._age} - {P2._age}");  
        }  
        static void Swap(ref object O1,ref object O2)  
        {  
            Object O = O1;  
            O1 = O2;  
            O2 = O;  
        }  
    }  
}  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,906 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,731 Reputation points
    2022-10-22T01:21:29.667+00:00

    A ref parameter means that the method (Swap in this case) can re-point your P1 and P2 references to other objects. It would cause issues if the compiler let you assign objects of types that are incompatible with Person to those variables.

    For example if you had a Car class you wouldn't want the compiler to let you assign that to your P1 and P2 references just on the basis that it's derived from Object because it's not derived from Person at all, and as such isn't guarantied to share the same methods, fields & properties, meaning a Car object probably won't be interchangeable with a Person object.

    You could however infer the type based on your usage with Generics:
    https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics

       static void Swap<T>(ref T O1, ref T O2)   
        {  
            T O = O1;  
            O1 = O2;  
            O2 = O;  
        }  
    

    Here the compiler can work out that you're passing in a Person and it'll insert that into this dynamic T argument, ensuring that O1 and O2 are the same type, and also that T is the same as the types of the variables you're refing them in to.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.