For Reference type, Is there any symbol can represent that I don't want to change it?

兰树豪 381 Reputation points
2023-05-31T12:50:05.8866667+00:00

See the code, For Reference type, is there any symbol can represent I just want to pass the instance as a value? dont want to chang it

 internal class Program
    {
        static void Main(string[] args)
        {
            RefType refType = new();
            refType.Name = "Original name ";
            ChangeName(refType);//is there any symbol here can  represent that I don't 
									//want to change original instance
                                  //just want to us it? 
            Console.WriteLine(refType.Name);
        }

        static RefType ChangeName(RefType rt)
        {
            rt.Name = "name  changed";
            return rt;
        }
    }

    class RefType 
    {
        public string Name { get; set; }

    }

Developer technologies | Windows Presentation Foundation
Developer technologies | .NET | Other
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
Developer technologies | C#
Developer technologies | 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.
{count} votes

Answer accepted by question author
  1. Viorel 125.3K Reputation points
    2023-05-31T13:52:17.5133333+00:00

    Maybe you can do something like this:

    interface IReadonlyRefType
    {
        public string Name { get; }
    
    }
    
    class RefType : IReadonlyRefType
    {
        public string Name { get; set; }
    }
    
    static void Test1( RefType rt )
    {
        rt.Name = "name  changed"; // OK
    }
    
    static void Test2( IReadonlyRefType rt )
    {
        string n = rt.Name; // OK
    
        //rt.Name = "name  changed"; // Error
    }
    
    // Usage:
    RefType refType = new();
    refType.Name = "Original name ";
    Test1(refType);
    Test2(refType);
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. David Lowndes 2,745 Reputation points MVP
    2023-05-31T12:56:00.1733333+00:00

    You can't change it where you indicate, but you could change:
    class RefType

    to

    struct RefType


Your answer

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