Error with in this
and ref this
as Parameters in Static Method Calls
#8059
-
Hello everyone, I'm working on a C# 12 project and encountering errors when using in this and ref this as parameters in static method calls. Below is a snippet of the code that's causing the issues: public class ClassA
{
public void MethodA()
{
ClassWithStaticMethod.StaticMethodWithIn(this);
// Error occurs here
ClassWithStaticMethod.StaticMethodWithIn(in this);
// Error occurs here
ClassWithStaticMethod.StaticMethodWithRefReadonly(ref this);
ClassWithStaticMethod.StaticMethodWithRefReadonly(this);
}
}
public class ClassWithStaticMethod
{
public static void StaticMethodWithIn(in ClassA classA)
{
Console.WriteLine("Static Method with in");
}
public static void StaticMethodWithRefReadonly(ref readonly ClassA classA)
{
Console.WriteLine("Static Method with ref readonly");
}
} When attempting to pass
Thank you for any explanations or workarounds you might suggest! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
@aa89227 The question shouldn't be why the language not doing what you might expect or why the compiler enforces it but why do you think it should work? not to mention that both of the examples that do work implicitly pass reference by |
Beta Was this translation helpful? Give feedback.
-
This is intentional and the whole purpose of
|
Beta Was this translation helpful? Give feedback.
This is intentional and the whole purpose of
ref readonly
feature.in x
must be used with a location (field or local variable). When passing valuex
, the compiler will implicitly assign a locationy = x
and passin y
.ref readonly
disallows such implicit variable.this
is a value, not stored a particular location. The same applies to string literals etc. You can't sayin "abc"
either.