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; }

    }

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,637 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,877 questions
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,639 questions
{count} votes

Accepted answer
  1. Viorel 114.7K 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,510 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