Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark some fields readonly or const #100728

Merged
merged 1 commit into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static partial class Marshal
/// <summary>
/// IUnknown is {00000000-0000-0000-C000-000000000046}
/// </summary>
internal static Guid IID_IUnknown = new Guid(0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46);
internal static readonly Guid IID_IUnknown = new Guid(0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46);
#endif //FEATURE_COMINTEROP

internal static int SizeOfHelper(RuntimeType t, [MarshalAs(UnmanagedType.Bool)] bool throwIfNotMarshalable)
Expand Down Expand Up @@ -929,7 +929,7 @@ public static object BindToMoniker(string monikerName)
ThrowExceptionForHR(MkParseDisplayName(bindctx, monikerName, out _, out IntPtr pmoniker));
try
{
ThrowExceptionForHR(BindMoniker(pmoniker, 0, ref IID_IUnknown, out IntPtr ptr));
ThrowExceptionForHR(BindMoniker(pmoniker, 0, in IID_IUnknown, out IntPtr ptr));
try
{
return GetObjectForIUnknown(ptr);
Expand All @@ -956,7 +956,7 @@ public static object BindToMoniker(string monikerName)
private static partial int MkParseDisplayName(IntPtr pbc, [MarshalAs(UnmanagedType.LPWStr)] string szUserName, out uint pchEaten, out IntPtr ppmk);

[LibraryImport(Interop.Libraries.Ole32)]
private static partial int BindMoniker(IntPtr pmk, uint grfOpt, ref Guid iidResult, out IntPtr ppvResult);
private static partial int BindMoniker(IntPtr pmk, uint grfOpt, in Guid iidResult, out IntPtr ppvResult);

[SupportedOSPlatform("windows")]
public static void ChangeWrapperHandleStrength(object otp, bool fIsWeak)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ public static void FailedAllocation(MethodTable* pEEType, bool fIsOverflow)
}

#if !INPLACE_RUNTIME
private static OutOfMemoryException s_theOOMException = new OutOfMemoryException();
private static readonly OutOfMemoryException s_theOOMException = new OutOfMemoryException();

// MRT exports GetRuntimeException for the few cases where we have a helper that throws an exception
// and may be called by either MRT or other classlibs and that helper needs to throw an exception.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ internal static class TypeCast
private const int MaximumCacheSize = 4096; // 4096 * sizeof(CastCacheEntry) is 98304 bytes on 64bit. We will rarely need this much though.
#endif // DEBUG

private static CastCache s_castCache = new CastCache(InitialCacheSize, MaximumCacheSize);
private static readonly CastCache s_castCache = new CastCache(InitialCacheSize, MaximumCacheSize);

[Flags]
internal enum AssignmentVariation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ public override int GetHashCode()

internal sealed class CustomMarshallerTable : ConcurrentUnifier<CustomMarshallerKey, object>
{
internal static CustomMarshallerTable s_customMarshallersTable = new CustomMarshallerTable();
internal static readonly CustomMarshallerTable s_customMarshallersTable = new CustomMarshallerTable();

protected override unsafe object Factory(CustomMarshallerKey key)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ namespace Internal.Runtime.CompilerServices
{
public class MethodNameAndSignature
{
public string Name { get; private set; }
public RuntimeSignature Signature { get; private set; }
public string Name { get; }
public RuntimeSignature Signature { get; }

public MethodNameAndSignature(string name, RuntimeSignature signature)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ internal static unsafe RuntimeType GetTypeFromMethodTable(MethodTable* pMT)

private static class AllocationLockHolder
{
public static Lock AllocationLock = new Lock(useTrivialWaits: true);
public static readonly Lock AllocationLock = new Lock(useTrivialWaits: true);
}

[MethodImpl(MethodImplOptions.NoInlining)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ internal static MethodBaseInvoker CreateMethodInvoker(RuntimeTypeHandle declarin
return new InstanceMethodInvoker(methodInvokeInfo, declaringTypeHandle);
}

internal MethodInvokeInfo MethodInvokeInfo { get; private set; }
internal MethodInvokeInfo MethodInvokeInfo { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Internal.TypeSystem
{
public class LockFreeObjectInterner : LockFreeReaderHashtableOfPointers<object, GCHandle>
{
private static LockFreeObjectInterner s_interner = new LockFreeObjectInterner();
private static readonly LockFreeObjectInterner s_interner = new LockFreeObjectInterner();
public static GCHandle GetInternedObjectHandle(object obj)
{
return s_interner.GetOrCreateValue(obj);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public unsafe class ModuleInfo
/// <summary>
/// Module handle is the TypeManager associated with this module.
/// </summary>
public TypeManagerHandle Handle { get; private set; }
public TypeManagerHandle Handle { get; }

/// <summary>
/// Initialize module info and construct per-module metadata reader.
Expand Down Expand Up @@ -49,7 +49,7 @@ internal NativeFormatModuleInfo(TypeManagerHandle moduleHandle, IntPtr pBlob, in
/// <summary>
/// Module metadata reader for NativeFormat metadata
/// </summary>
public MetadataReader MetadataReader { get; private set; }
public MetadataReader MetadataReader { get; }

internal unsafe bool TryFindBlob(ReflectionMapBlob blobId, out byte* pBlob, out uint cbBlob)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static class TypeSystemContextFactory
// This allows us to avoid recreating the type resolution context again and again, but still allows it to go away once the types are no longer being built
private static GCHandle s_cachedContext = GCHandle.Alloc(null, GCHandleType.Weak);

private static Lock s_lock = new Lock(useTrivialWaits: true);
private static readonly Lock s_lock = new Lock(useTrivialWaits: true);

public static TypeSystemContext Create()
{
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/tools/Common/Pgo/PgoFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ public static void EncodePgoData<TType, TMethod>(IEnumerable<PgoSchemaElem> sche

private sealed class PgoSchemaMergeComparer : IComparer<PgoSchemaElem>, IEqualityComparer<PgoSchemaElem>
{
public static PgoSchemaMergeComparer Singleton = new PgoSchemaMergeComparer();
public static readonly PgoSchemaMergeComparer Singleton = new PgoSchemaMergeComparer();

public int Compare(PgoSchemaElem x, PgoSchemaElem y)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Internal.TypeSystem
/// </summary>
public sealed class BaseTypeRuntimeInterfacesAlgorithm : RuntimeInterfacesAlgorithm
{
private static RuntimeInterfacesAlgorithm _singleton = new BaseTypeRuntimeInterfacesAlgorithm();
private static readonly RuntimeInterfacesAlgorithm _singleton = new BaseTypeRuntimeInterfacesAlgorithm();

private BaseTypeRuntimeInterfacesAlgorithm() { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ private sealed class EmbeddedSignatureDataEmitter
private Stack<int> _indexStack = new Stack<int>();
private TypeSystemMetadataEmitter _metadataEmitter;

public static EmbeddedSignatureDataEmitter EmptySingleton = new EmbeddedSignatureDataEmitter(null, null);
public static readonly EmbeddedSignatureDataEmitter EmptySingleton = new EmbeddedSignatureDataEmitter(null, null);

public EmbeddedSignatureDataEmitter(EmbeddedSignatureData[] embeddedData, TypeSystemMetadataEmitter metadataEmitter)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ protected override ObjectNodeSection GetDehydratedSection(NodeFactory factory)
return ObjectNodeSection.DataSection;
}

private static Utf8String s_NativeLayoutSignaturePrefix = new Utf8String("__RFHSignature_");
private static readonly Utf8String s_NativeLayoutSignaturePrefix = new Utf8String("__RFHSignature_");

protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFact
return dependencies;
}

private static Utf8String s_NativeLayoutSignaturePrefix = new Utf8String("__RMHSignature_");
private static readonly Utf8String s_NativeLayoutSignaturePrefix = new Utf8String("__RMHSignature_");

protected override ObjectData GetDehydratableData(NodeFactory factory, bool relocsOnly = false)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysisFramework
/// <typeparam name="DependencyContextType"></typeparam>
public struct NoLogStrategy<DependencyContextType> : IDependencyAnalysisMarkStrategy<DependencyContextType>
{
private static object s_singleton = new object();
private static readonly object s_singleton = new object();

bool IDependencyAnalysisMarkStrategy<DependencyContextType>.MarkNode(
DependencyNodeCore<DependencyContextType> node,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ internal static partial class HttpApi
{
internal static readonly HTTPAPI_VERSION s_version = new HTTPAPI_VERSION() { HttpApiMajorVersion = 2, HttpApiMinorVersion = 0 };
internal static readonly bool s_supported = InitHttpApi(s_version);
internal static IPEndPoint s_any = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort);
internal static IPEndPoint s_ipv6Any = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort);
internal static readonly IPEndPoint s_any = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort);
internal static readonly IPEndPoint s_ipv6Any = new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort);
internal const int IPv4AddressSize = 16;
internal const int IPv6AddressSize = 28;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ internal static partial class Oids
internal static Oid CommonNameOid => s_commonNameOid ??= InitializeOid(CommonName);
internal static Oid CountryOrRegionNameOid => s_countryOrRegionOid ??= InitializeOid(CountryOrRegionName);
internal static Oid LocalityNameOid => s_localityNameOid ??= InitializeOid(LocalityName);
internal static Oid StateOrProvinceNameOid = s_stateOrProvinceNameOid ??= InitializeOid(StateOrProvinceName);
internal static Oid OrganizationOid = s_organizationOid ??= InitializeOid(Organization);
internal static Oid OrganizationalUnitOid = s_organizationalUnitOid ??= InitializeOid(OrganizationalUnit);
internal static Oid EmailAddressOid = s_emailAddressOid ??= InitializeOid(EmailAddress);
internal static Oid StateOrProvinceNameOid => s_stateOrProvinceNameOid ??= InitializeOid(StateOrProvinceName);
internal static Oid OrganizationOid => s_organizationOid ??= InitializeOid(Organization);
internal static Oid OrganizationalUnitOid => s_organizationalUnitOid ??= InitializeOid(OrganizationalUnit);
internal static Oid EmailAddressOid => s_emailAddressOid ??= InitializeOid(EmailAddress);

private static Oid InitializeOid(string oidValue)
{
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/Microsoft.Bcl.Numerics/src/System/MathF.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static class MathF
/// </summary>
public const float E = 2.71828183f;

private static float NegativeZero = Int32BitsToSingle(unchecked((int)0x80000000));
private static readonly float NegativeZero = Int32BitsToSingle(unchecked((int)0x80000000));

private static unsafe float Int32BitsToSingle(int value)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public CommandLineConfigurationProvider(IEnumerable<string> args, IDictionary<st
/// <summary>
/// The command line arguments.
/// </summary>
protected IEnumerable<string> Args { get; private set; }
protected IEnumerable<string> Args { get; }

/// <summary>
/// Loads the configuration data from the command line args.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Microsoft.Extensions.DependencyInjection
{
internal sealed class CallSiteJsonFormatter : CallSiteVisitor<CallSiteJsonFormatter.CallSiteFormatterContext, object?>
{
internal static CallSiteJsonFormatter Instance = new CallSiteJsonFormatter();
internal static readonly CallSiteJsonFormatter Instance = new CallSiteJsonFormatter();

private CallSiteJsonFormatter()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.Extensions.DependencyModel
{
internal sealed class EnvironmentWrapper : IEnvironment
{
public static IEnvironment Default = new EnvironmentWrapper();
public static readonly IEnvironment Default = new EnvironmentWrapper();

public string? GetEnvironmentVariable(string name) => Environment.GetEnvironmentVariable(name);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public ActiveHandlerTrackingEntry(
_lock = new object();
}

public LifetimeTrackingHttpMessageHandler Handler { get; private set; }
public LifetimeTrackingHttpMessageHandler Handler { get; }

public TimeSpan Lifetime { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public LogValuesFormatter(string format)
#endif
}

public string OriginalFormat { get; private set; }
public string OriginalFormat { get; }
public List<string> ValueNames => _valueNames;

private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ internal sealed class CDSCollectionETWBCLProvider : EventSource
/// Defines the singleton instance for the collection ETW provider.
/// The collection provider GUID is {35167F8E-49B2-4b96-AB86-435B59336B5E}.
/// </summary>
public static CDSCollectionETWBCLProvider Log = new CDSCollectionETWBCLProvider();
public static readonly CDSCollectionETWBCLProvider Log = new CDSCollectionETWBCLProvider();
/// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary>
private CDSCollectionETWBCLProvider() { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public virtual IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicParti
/// <summary>
/// Gets whether elements in each partition are yielded in the order of increasing keys.
/// </summary>
public bool KeysOrderedInEachPartition { get; private set; }
public bool KeysOrderedInEachPartition { get; }

/// <summary>
/// Gets whether elements in an earlier partition always come before elements in a later partition.
Expand All @@ -141,7 +141,7 @@ public virtual IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicParti
/// smaller order key than any element in partition 1, each element in partition 1 has a smaller
/// order key than any element in partition 2, and so on.
/// </remarks>
public bool KeysOrderedAcrossPartitions { get; private set; }
public bool KeysOrderedAcrossPartitions { get; }

/// <summary>
/// Gets whether order keys are normalized.
Expand All @@ -151,7 +151,7 @@ public virtual IEnumerable<KeyValuePair<long, TSource>> GetOrderableDynamicParti
/// [0 .. numberOfElements-1]. If the property returns false, order keys must still be distinct, but
/// only their relative order is considered, not their absolute values.
/// </remarks>
public bool KeysNormalized { get; private set; }
public bool KeysNormalized { get; }

/// <summary>
/// Partitions the underlying collection into the given number of ordered partitions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ private abstract class DynamicPartitionEnumerator_Abstract<TSource, TSourceReade
//--- shared by all derived class with source data type: IList, Array, and IEnumerator
protected readonly TSourceReader _sharedReader;

protected static int s_defaultMaxChunkSize = GetDefaultChunkSize<TSource>();
protected static readonly int s_defaultMaxChunkSize = GetDefaultChunkSize<TSource>();

//deferred allocating in MoveNext() with initial value 0, to avoid false sharing
//we also use the fact that: (_currentChunkSize==null) means MoveNext is never called on this enumerator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class PartBuilder
private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportBuilder>, Type>> _propertyImports;
private readonly List<Tuple<Predicate<Type>, Action<Type, ExportBuilder>>> _interfaceExports;

internal Predicate<Type> SelectType { get; private set; }
internal Predicate<Type> SelectType { get; }

internal PartBuilder(Predicate<Type> selectType)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public ExportAttribute(string? contractName, Type? contractType)
/// A <see cref="string"/> containing the contract name to export the type or member
/// marked with this attribute, under. The default value is an empty string ("").
/// </value>
public string? ContractName { get; private set; }
public string? ContractName { get; }

/// <summary>
/// Get the contract type that is exported by the member that this attribute is attached to.
Expand All @@ -136,6 +136,6 @@ public ExportAttribute(string? contractName, Type? contractType)
/// <see langword="null"/> which means that the type will be obtained by looking at the type on
/// the member that this export is attached to.
/// </value>
public Type? ContractType { get; private set; }
public Type? ContractType { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1025,7 +1025,7 @@ public CatalogPart(ComposablePart part)
{
Part = part;
}
public ComposablePart Part { get; private set; }
public ComposablePart Part { get; }

public bool ImportsSatisfied
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,6 @@ public IEnumerable<ComposablePartDefinition> RemovedDefinitions
/// When the value is non-null it should be used to record temporary changed state
/// and actions that will be executed when the atomicComposition is completeed.
/// </value>
public AtomicComposition? AtomicComposition { get; private set; }
public AtomicComposition? AtomicComposition { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,6 @@ public IEnumerable<ExportDefinition> RemovedExports
/// When the value is non-null it should be used to record temporary changed state
/// and actions that will be executed when the atomicComposition is completeed.
/// </value>
public AtomicComposition? AtomicComposition { get; private set; }
public AtomicComposition? AtomicComposition { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public ImportAttribute(string? contractName, Type? contractType)
/// A <see cref="string"/> containing the contract name of the export to import. The
/// default value is an empty string ("").
/// </value>
public string? ContractName { get; private set; }
public string? ContractName { get; }

/// <summary>
/// Get the contract type of the export to import.
Expand All @@ -110,7 +110,7 @@ public ImportAttribute(string? contractName, Type? contractType)
/// the member that this import is attached to. If the type is <see cref="object"/> then the
/// importer is delaring they can accept any exported type.
/// </value>
public Type? ContractType { get; private set; }
public Type? ContractType { get; }

/// <summary>
/// Gets or sets a value indicating whether the property, field or parameter will be set
Expand Down
Loading
Loading