diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs index d090f3300cdb29..c1228bc1eade72 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComRuntimeHelpers.cs @@ -166,7 +166,7 @@ internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch) return typeInfo; } - internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo) + internal static unsafe ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo) { IntPtr pAttrs; typeInfo.GetTypeAttr(out pAttrs); @@ -179,7 +179,7 @@ internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo type try { - return (ComTypes.TYPEATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPEATTR)); + return *(ComTypes.TYPEATTR*)pAttrs; } finally { @@ -187,7 +187,7 @@ internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo type } } - internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib) + internal static unsafe ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib) { IntPtr pAttrs; typeLib.GetLibAttr(out pAttrs); @@ -200,7 +200,7 @@ internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typ try { - return (ComTypes.TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPELIBATTR)); + return *(ComTypes.TYPELIBATTR*)pAttrs; } finally { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs index 0d9b7998872d41..26e526a28f3c36 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeEnumDesc.cs @@ -36,7 +36,7 @@ internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc try { - varDesc = (ComTypes.VARDESC)Marshal.PtrToStructure(p, typeof(ComTypes.VARDESC)); + varDesc = Marshal.PtrToStructure(p); if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST) { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ExcepInfo.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ExcepInfo.cs index 7d65926d813c99..b839dbb7d21db8 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ExcepInfo.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ExcepInfo.cs @@ -29,7 +29,7 @@ internal struct ExcepInfo #if DEBUG static ExcepInfo() { - Debug.Assert(Marshal.SizeOf(typeof(ExcepInfo)) == Marshal.SizeOf(typeof(ComTypes.EXCEPINFO))); + Debug.Assert(Marshal.SizeOf() == Marshal.SizeOf()); } #endif diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs index 5e1f62f83d7c00..f4ee622d505f0f 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchComObject.cs @@ -328,7 +328,7 @@ DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) return new IDispatchMetaObject(parameter, this); } - private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle) + private static unsafe void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle) { IntPtr pFuncDesc; typeInfo.GetFuncDesc(funcIndex, out pFuncDesc); @@ -339,7 +339,7 @@ private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int fun throw Error.CannotRetrieveTypeInformation(); } - funcDesc = (ComTypes.FUNCDESC)Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes.FUNCDESC)); + funcDesc = *(ComTypes.FUNCDESC*)pFuncDesc; funcDescHandle = pFuncDesc; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs index b2f31a5eaf56dd..451cdd5434697f 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs @@ -1439,7 +1439,7 @@ private static void SetParameterDataForMethProp(MethodOrPropertySymbol methProp, if (parameters.Length > 0) { // See if we have a param array. - if (parameters[parameters.Length - 1].GetCustomAttribute(typeof(ParamArrayAttribute), false) != null) + if (parameters[parameters.Length - 1].GetCustomAttribute(false) != null) { methProp.isParamArray = true; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs index 788b20f5be1932..1f1f1cef1a4e8c 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.Keyed.cs @@ -327,7 +327,6 @@ public static IServiceCollection AddKeyedScoped( return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } - /// /// Adds a singleton service of the type specified in with an /// implementation of the type specified in to the diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb index 45fe6e29b9a1ea..27ac1fec7e5970 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/FileSystem.vb @@ -892,7 +892,7 @@ Namespace Microsoft.VisualBasic.FileIO Private Shared Sub CopyOrMoveDirectory(ByVal operation As CopyOrMove, ByVal sourceDirectoryName As String, ByVal destinationDirectoryName As String, ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption) - Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation") + Debug.Assert([Enum].IsDefined(operation), "Invalid Operation") ' Verify enums. VerifyUICancelOption("onUserCancel", onUserCancel) @@ -961,7 +961,7 @@ Namespace Microsoft.VisualBasic.FileIO Private Shared Sub FxCopyOrMoveDirectory(ByVal operation As CopyOrMove, ByVal sourceDirectoryPath As String, ByVal targetDirectoryPath As String, ByVal overwrite As Boolean) - Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation") + Debug.Assert([Enum].IsDefined(operation), "Invalid Operation") Debug.Assert(sourceDirectoryPath <> "" And IO.Path.IsPathRooted(sourceDirectoryPath), "Invalid Source") Debug.Assert(targetDirectoryPath <> "" And IO.Path.IsPathRooted(targetDirectoryPath), "Invalid Target") @@ -1010,7 +1010,7 @@ Namespace Microsoft.VisualBasic.FileIO Private Shared Sub CopyOrMoveDirectoryNode(ByVal Operation As CopyOrMove, ByVal SourceDirectoryNode As DirectoryNode, ByVal Overwrite As Boolean, ByVal Exceptions As ListDictionary) - Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), Operation), "Invalid Operation") + Debug.Assert([Enum].IsDefined(Operation), "Invalid Operation") Debug.Assert(Exceptions IsNot Nothing, "Null exception list") Debug.Assert(SourceDirectoryNode IsNot Nothing, "Null source node") @@ -1092,7 +1092,7 @@ Namespace Microsoft.VisualBasic.FileIO ByVal sourceFileName As String, ByVal destinationFileName As String, ByVal overwrite As Boolean, ByVal showUI As UIOptionInternal, ByVal onUserCancel As UICancelOption ) - Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), operation), "Invalid Operation") + Debug.Assert([Enum].IsDefined(operation), "Invalid Operation") ' Verify enums. VerifyUICancelOption("onUserCancel", onUserCancel) @@ -1597,8 +1597,8 @@ Namespace Microsoft.VisualBasic.FileIO ''' Private Shared Sub ShellCopyOrMove(ByVal Operation As CopyOrMove, ByVal TargetType As FileOrDirectory, ByVal FullSourcePath As String, ByVal FullTargetPath As String, ByVal ShowUI As UIOptionInternal, ByVal OnUserCancel As UICancelOption) - Debug.Assert(System.Enum.IsDefined(GetType(CopyOrMove), Operation)) - Debug.Assert(System.Enum.IsDefined(GetType(FileOrDirectory), TargetType)) + Debug.Assert([Enum].IsDefined(Operation)) + Debug.Assert([Enum].IsDefined(TargetType)) Debug.Assert(FullSourcePath <> "" And IO.Path.IsPathRooted(FullSourcePath), "Invalid FullSourcePath") Debug.Assert(FullTargetPath <> "" And IO.Path.IsPathRooted(FullTargetPath), "Invalid FullTargetPath") Debug.Assert(ShowUI <> UIOptionInternal.NoUI, "Why call ShellDelete if ShowUI is NoUI???") @@ -1693,7 +1693,7 @@ Namespace Microsoft.VisualBasic.FileIO Private Shared Sub ShellFileOperation(ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags, ByVal FullSource As String, ByVal FullTarget As String, ByVal OnUserCancel As UICancelOption, ByVal FileOrDirectory As FileOrDirectory) - Debug.Assert(System.Enum.IsDefined(GetType(SHFileOperationType), OperationType)) + Debug.Assert([Enum].IsDefined(OperationType)) Debug.Assert(OperationType <> SHFileOperationType.FO_RENAME, "Don't call Shell to rename") Debug.Assert(FullSource <> "" And IO.Path.IsPathRooted(FullSource), "Invalid FullSource path") Debug.Assert(OperationType = SHFileOperationType.FO_DELETE OrElse (FullTarget <> "" And IO.Path.IsPathRooted(FullTarget)), "Invalid FullTarget path") @@ -1750,7 +1750,7 @@ Namespace Microsoft.VisualBasic.FileIO Private Shared Function GetShellOperationInfo( ByVal OperationType As SHFileOperationType, ByVal OperationFlags As ShFileOperationFlags, ByVal SourcePaths() As String, Optional ByVal TargetPath As String = Nothing) As SHFILEOPSTRUCT - Debug.Assert(System.Enum.IsDefined(GetType(SHFileOperationType), OperationType), "Invalid OperationType") + Debug.Assert([Enum].IsDefined(OperationType), "Invalid OperationType") Debug.Assert(TargetPath = "" Or IO.Path.IsPathRooted(TargetPath), "Invalid TargetPath") Debug.Assert(SourcePaths IsNot Nothing AndAlso SourcePaths.Length > 0, "Invalid SourcePaths") diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs index d87deab820434c..aa28f466deeb47 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs @@ -312,7 +312,7 @@ public virtual void EndNew(int itemIndex) { // Allow event handler to supply the new item for us // If event handler did not supply new item, create one ourselves - object? newItem = FireAddingNew() ?? Activator.CreateInstance(typeof(T)); + object? newItem = FireAddingNew() ?? Activator.CreateInstance(); // Add item to end of list. Note: If event handler returned an item not of type T, // the cast below will trigger an InvalidCastException. This is by design. diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs index 2d6d63fee72970..d488ad57dc2bdb 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SidList.cs @@ -62,7 +62,7 @@ internal SidList(Interop.SID_AND_ATTRIBUTES[] sidAndAttr) TranslateSids(null, pSids); } - private void TranslateSids(string target, IntPtr[] pSids) + private unsafe void TranslateSids(string target, IntPtr[] pSids) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: processing {0} SIDs", pSids.Length); @@ -157,8 +157,8 @@ private void TranslateSids(string target, IntPtr[] pSids) for (int i = 0; i < domainCount; i++) { - domains[i] = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(pCurrentDomain, typeof(Interop.LSA_TRUST_INFORMATION)); - pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(Interop.LSA_TRUST_INFORMATION))); + domains[i] = *(Interop.LSA_TRUST_INFORMATION*)pCurrentDomain; + pCurrentDomain += sizeof(Interop.LSA_TRUST_INFORMATION); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", sidCount, domainCount); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs index b9423466e825da..73c71722cc2ca2 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AuthZSet.cs @@ -131,7 +131,7 @@ out pClientContext // Extract TOKEN_GROUPS.GroupCount - Interop.TOKEN_GROUPS tokenGroups = (Interop.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_GROUPS)); + Interop.TOKEN_GROUPS tokenGroups = *(Interop.TOKEN_GROUPS*)pBuffer; uint groupCount = tokenGroups.GroupCount; @@ -141,13 +141,13 @@ out pClientContext // each native SID_AND_ATTRIBUTES into a managed SID_AND_ATTR. Interop.SID_AND_ATTRIBUTES[] groups = new Interop.SID_AND_ATTRIBUTES[groupCount]; - IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(Interop.TOKEN_GROUPS)) - sizeof(Interop.SID_AND_ATTRIBUTES)); + IntPtr currentItem = pBuffer + sizeof(Interop.TOKEN_GROUPS) - sizeof(Interop.SID_AND_ATTRIBUTES); for (int i = 0; i < groupCount; i++) { - groups[i] = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure(currentItem, typeof(Interop.SID_AND_ATTRIBUTES)); + groups[i] = *(Interop.SID_AND_ATTRIBUTES*)currentItem; - currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(Interop.SID_AND_ATTRIBUTES))); + currentItem += sizeof(Interop.SID_AND_ATTRIBUTES); } _groupSidList = new SidList(groups); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index 1f91a0e5daccd6..f31b35ca0c22b4 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -1053,7 +1053,7 @@ private void LoadComputerInfo() if (err == 0) { UnsafeNativeMethods.WKSTA_INFO_100 wkstaInfo = - (UnsafeNativeMethods.WKSTA_INFO_100)Marshal.PtrToStructure(buffer, typeof(UnsafeNativeMethods.WKSTA_INFO_100)); + Marshal.PtrToStructure(buffer); _machineFlatName = wkstaInfo.wki100_computername; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "LoadComputerInfo: machineFlatName={0}", _machineFlatName); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs index 619c48191e264e..c4995b0a2c53e5 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs @@ -198,15 +198,14 @@ internal static SidType ClassifySID(byte[] sid) } - internal static SidType ClassifySID(IntPtr pSid) + internal static unsafe SidType ClassifySID(IntPtr pSid) { Debug.Assert(Interop.Advapi32.IsValidSid(pSid)); // Get the issuing authority and the first RID IntPtr pIdentAuth = Interop.Advapi32.GetSidIdentifierAuthority(pSid); - Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = - (Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)); + Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = *(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY*)pIdentAuth; IntPtr pRid = Interop.Advapi32.GetSidSubAuthority(pSid, 0); int rid = Marshal.ReadInt32(pRid); @@ -333,7 +332,7 @@ internal static bool IsSamUser() } - internal static IntPtr GetCurrentUserSid() + internal static unsafe IntPtr GetCurrentUserSid() { SafeTokenHandle tokenHandle = null; IntPtr pBuffer = IntPtr.Zero; @@ -425,7 +424,7 @@ out tokenHandle } // Retrieve the user's SID from the user info - Interop.TOKEN_USER tokenUser = (Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(Interop.TOKEN_USER)); + Interop.TOKEN_USER tokenUser = *(Interop.TOKEN_USER*)pBuffer; IntPtr pUserSid = tokenUser.sidAndAttributes.Sid; // this is a reference into the NATIVE memory (into pBuffer) Debug.Assert(Interop.Advapi32.IsValidSid(pUserSid)); @@ -457,7 +456,7 @@ out tokenHandle } - internal static IntPtr GetMachineDomainSid() + internal static unsafe IntPtr GetMachineDomainSid() { SafeLsaPolicyHandle policyHandle = null; IntPtr pBuffer = IntPtr.Zero; @@ -496,8 +495,7 @@ internal static IntPtr GetMachineDomainSid() } Debug.Assert(pBuffer != IntPtr.Zero); - UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO) - Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)); + UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = *(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO*)pBuffer; Debug.Assert(Interop.Advapi32.IsValidSid(info.DomainSid)); @@ -570,7 +568,7 @@ internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string comput } UnsafeNativeMethods.DomainControllerInfo domainControllerInfo = - (UnsafeNativeMethods.DomainControllerInfo)Marshal.PtrToStructure(domainControllerInfoPtr, typeof(UnsafeNativeMethods.DomainControllerInfo)); + Marshal.PtrToStructure(domainControllerInfoPtr); return domainControllerInfo; } @@ -802,7 +800,7 @@ internal static bool IsMachineDC(string computerName) } UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC dsRolePrimaryDomainInfo = - (UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)Marshal.PtrToStructure(dsRoleInfoPtr, typeof(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)); + Marshal.PtrToStructure(dsRoleInfoPtr); return (dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController || dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs index 7e37a4c15175c5..13f7b8b0963a78 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs @@ -527,7 +527,7 @@ private static unsafe int EncodingMultiByteArrayHelper(SafeBerHandle berElement, { int i = 0; berValArray = Utility.AllocHGlobalIntPtrArray(tempValue.Length + 1); - int structSize = Marshal.SizeOf(typeof(BerVal)); + int structSize = Marshal.SizeOf(); managedBervalArray = new BerVal[tempValue.Length]; void** pBerValArray = (void**)berValArray; diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs index 31548f6b2fd639..f47bc50318b946 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs @@ -716,7 +716,7 @@ public override unsafe byte[] GetValue() } IntPtr control = IntPtr.Zero; - int structSize = Marshal.SizeOf(typeof(SortKeyInterop)); + int structSize = Marshal.SizeOf(); int keyCount = nativeSortKeys.Length; IntPtr memHandle = Utility.AllocHGlobalIntPtrArray(keyCount + 1); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index 0d478c6167ca1f..4be0407a9eea9b 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -544,7 +544,7 @@ private unsafe int SendRequestHelper(DirectoryRequest request, ref int messageID { // Build server control. managedServerControls = BuildControlArray(request.Controls, true); - int structSize = Marshal.SizeOf(typeof(LdapControl)); + int structSize = Marshal.SizeOf(); if (managedServerControls != null) { @@ -658,7 +658,7 @@ private unsafe int SendRequestHelper(DirectoryRequest request, ref int messageID addModCount = (modifications == null ? 1 : modifications.Length + 1); modArray = Utility.AllocHGlobalIntPtrArray(addModCount); void** pModArray = (void**)modArray; - int modStructSize = Marshal.SizeOf(typeof(LdapMod)); + int modStructSize = Marshal.SizeOf(); int i = 0; for (i = 0; i < addModCount - 1; i++) { @@ -918,12 +918,12 @@ private unsafe Interop.BOOL ProcessClientCertificate(IntPtr ldapHandle, IntPtr C var list = new ArrayList(); if (CAs != IntPtr.Zero) { - SecPkgContext_IssuerListInfoEx trustedCAs = (SecPkgContext_IssuerListInfoEx)Marshal.PtrToStructure(CAs, typeof(SecPkgContext_IssuerListInfoEx)); + SecPkgContext_IssuerListInfoEx trustedCAs = *(SecPkgContext_IssuerListInfoEx*)CAs; int issuerNumber = trustedCAs.cIssuers; for (int i = 0; i < issuerNumber; i++) { - IntPtr tempPtr = (IntPtr)((byte*)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * (nint)i); - CRYPTOAPI_BLOB info = (CRYPTOAPI_BLOB)Marshal.PtrToStructure(tempPtr, typeof(CRYPTOAPI_BLOB)); + IntPtr tempPtr = (IntPtr)((byte*)trustedCAs.aIssuers + sizeof(CRYPTOAPI_BLOB) * (nint)i); + CRYPTOAPI_BLOB info = *(CRYPTOAPI_BLOB*)tempPtr; int dataLength = info.cbData; byte[] context = new byte[dataLength]; @@ -1077,7 +1077,7 @@ private void BindHelper(NetworkCredential newCredential, bool needSetCredential) var cred = new SEC_WINNT_AUTH_IDENTITY_EX() { version = Interop.SEC_WINNT_AUTH_IDENTITY_VERSION, - length = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX)), + length = Marshal.SizeOf(), flags = Interop.SEC_WINNT_AUTH_IDENTITY_UNICODE }; if (AuthType == AuthType.Kerberos) @@ -1342,7 +1342,7 @@ internal static unsafe LdapMod[] BuildAttributes(CollectionBase directoryAttribu attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1); void** pAttributesValues = (void**)attributes[i].values; - int structSize = Marshal.SizeOf(typeof(BerVal)); + int structSize = Marshal.SizeOf(); IntPtr controlPtr; int m; diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs index 06809037a8ba47..0fa241fc30113d 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs @@ -555,7 +555,7 @@ public unsafe void StartTransportLayerSecurity(DirectoryControlCollection contro { // build server control managedServerControls = LdapConnection.BuildControlArray(controls, true); - int structSize = Marshal.SizeOf(typeof(LdapControl)); + int structSize = Marshal.SizeOf(); if (managedServerControls != null) { serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1); @@ -848,7 +848,7 @@ private void ProcessCallBackRoutine(ReferralCallback tempCallback) { LdapReferralCallback value = new LdapReferralCallback() { - sizeofcallback = Marshal.SizeOf(typeof(LdapReferralCallback)), + sizeofcallback = Marshal.SizeOf(), query = tempCallback.QueryForConnection == null ? null : _queryDelegate, notify = tempCallback.NotifyNewConnection == null ? null : _notifiyDelegate, dereference = tempCallback.DereferenceConnection == null ? null : _dereferenceDelegate diff --git a/src/libraries/System.DirectoryServices/src/Interop/EnumVariant.cs b/src/libraries/System.DirectoryServices/src/Interop/EnumVariant.cs index eb1ac26a1d094e..b8f3f3227e7f3c 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/EnumVariant.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/EnumVariant.cs @@ -58,10 +58,10 @@ public void Reset() /// Moves the pointer to the next value In the contained IEnumVariant, and /// stores the current value In currentValue. /// - private void Advance() + private unsafe void Advance() { _currentValue = s_noMoreValues; - IntPtr addr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Variant))); + IntPtr addr = Marshal.AllocCoTaskMem(sizeof(Variant)); try { int[] numRead = new int[] { 0 }; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs index baad123def5174..6dffd10fe38221 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs @@ -64,14 +64,14 @@ internal void AddHelper(int count, IntPtr info, bool advanced) { if (advanced) { - addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf(typeof(DS_REPL_ATTR_META_DATA_2))); + addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf()); AttributeMetadata managedMetaData = new AttributeMetadata(addr, true, _server, _nameTable); Add(managedMetaData.Name, managedMetaData); } else { - addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf(typeof(DS_REPL_ATTR_META_DATA))); + addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf()); AttributeMetadata managedMetaData = new AttributeMetadata(addr, false, _server, _nameTable); Add(managedMetaData.Name, managedMetaData); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs index d51219dafba672..1a50524bb1438e 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -1302,7 +1302,7 @@ private unsafe void GetDomains() DomainController dc = DomainController.GetDomainController(Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context)); IntPtr handle = dc.Handle; - Debug.Assert(handle != (IntPtr)0); + Debug.Assert(handle != 0); void* pDomains = null; // call DsReplicaSyncAllW @@ -1327,11 +1327,11 @@ private unsafe void GetDomains() IntPtr val = names.rItems; if (count > 0) { - Debug.Assert(val != (IntPtr)0); - IntPtr tmpPtr = (IntPtr)0; + Debug.Assert(val != 0); + IntPtr tmpPtr = 0; for (int i = 0; i < count; i++) { - tmpPtr = IntPtr.Add(val, Marshal.SizeOf(typeof(DS_NAME_RESULT_ITEM)) * i); + tmpPtr = IntPtr.Add(val, Marshal.SizeOf() * i); DS_NAME_RESULT_ITEM nameResult = new DS_NAME_RESULT_ITEM(); Marshal.PtrToStructure(tmpPtr, nameResult); if (nameResult.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || nameResult.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 6a742782d8f48a..4d7862649788d8 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -692,8 +692,8 @@ private unsafe void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLi internal unsafe void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string? sourceServer, int option, SafeLibraryHandle libHandle) { - int structSize = Marshal.SizeOf(typeof(Guid)); - IntPtr unmanagedGuid = (IntPtr)0; + int structSize = sizeof(Guid); + IntPtr unmanagedGuid = 0; Guid guid = Guid.Empty; AdamInstance? adamServer = null; DomainController? dcServer = null; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs index c216689bf0a072..a606eaf17bdf93 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs @@ -114,8 +114,8 @@ public unsafe void Save() { try { - IntPtr ptr = (IntPtr)0; - fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime))); + IntPtr ptr = 0; + fileTime = Marshal.AllocHGlobal(Marshal.SizeOf()); Interop.Kernel32.GetSystemTimeAsFileTime(fileTime); // set the time @@ -134,7 +134,7 @@ public unsafe void Save() ptrList.Add(ptr); Interop.NtDll.RtlInitUnicodeString(out record.TopLevelName, ptr); - tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); + tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); ptrList.Add(tmpPtr); Marshal.StructureToPtr(record, tmpPtr, false); @@ -163,7 +163,7 @@ public unsafe void Save() ptr = Marshal.StringToHGlobalUni(_excludedNames[i]); ptrList.Add(ptr); Interop.NtDll.RtlInitUnicodeString(out record.TopLevelName, ptr); - tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); + tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); ptrList.Add(tmpPtr); Marshal.StructureToPtr(record, tmpPtr, false); @@ -196,7 +196,7 @@ public unsafe void Save() ptrList.Add(record.DomainInfo.NetBIOSNameBuffer); record.DomainInfo.NetBIOSNameLength = (short)(tmp.NetBiosName == null ? 0 : tmp.NetBiosName.Length * 2); record.DomainInfo.NetBIOSNameMaximumLength = (short)(tmp.NetBiosName == null ? 0 : tmp.NetBiosName.Length * 2); - tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); + tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); ptrList.Add(tmpPtr); Marshal.StructureToPtr(record, tmpPtr, false); @@ -222,7 +222,7 @@ public unsafe void Save() ptrList.Add(record.Data.Buffer); Marshal.Copy((byte[])_binaryData[i]!, 0, record.Data.Buffer, record.Data.Length); } - tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD))); + tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); ptrList.Add(tmpPtr); Marshal.StructureToPtr(record, tmpPtr, false); @@ -235,7 +235,7 @@ public unsafe void Save() LSA_FOREST_TRUST_INFORMATION trustInformation = new LSA_FOREST_TRUST_INFORMATION(); trustInformation.RecordCount = count; trustInformation.Entries = records; - forestInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_INFORMATION))); + forestInfo = Marshal.AllocHGlobal(Marshal.SizeOf()); Marshal.StructureToPtr(trustInformation, forestInfo, false); // get policy server name diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs index 52e2946a207db0..6b109f8663b4ef 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs @@ -49,13 +49,13 @@ internal void AddHelper(string partition, object cursors, bool advanced, IntPtr else count = ((DS_REPL_CURSORS)cursors).cNumCursors; - IntPtr addr = (IntPtr)0; + IntPtr addr = 0; for (int i = 0; i < count; i++) { if (advanced) { - addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf(typeof(DS_REPL_CURSOR_3))); + addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf()); DS_REPL_CURSOR_3 cursor = new DS_REPL_CURSOR_3(); Marshal.PtrToStructure(addr, cursor); @@ -69,7 +69,7 @@ internal void AddHelper(string partition, object cursors, bool advanced, IntPtr } else { - addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf(typeof(DS_REPL_CURSOR))); + addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf()); DS_REPL_CURSOR cursor = new DS_REPL_CURSOR(); Marshal.PtrToStructure(addr, cursor); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs index fcf99e14cf3d32..d67221932fc3d2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs @@ -48,11 +48,11 @@ internal void AddHelper(DS_REPL_KCC_DSA_FAILURES failures, IntPtr info) // get the count int count = failures.cNumEntries; - IntPtr addr = (IntPtr)0; + IntPtr addr = 0; for (int i = 0; i < count; i++) { - addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf(typeof(DS_REPL_KCC_DSA_FAILURE))); + addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf()); ReplicationFailure managedFailure = new ReplicationFailure(addr, _server, _nameTable); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs index 34f7203e9f520a..476a7591ef75b1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs @@ -48,11 +48,11 @@ internal void AddHelper(DS_REPL_NEIGHBORS neighbors, IntPtr info) // get the count int count = neighbors.cNumNeighbors; - IntPtr addr = (IntPtr)0; + IntPtr addr = 0; for (int i = 0; i < count; i++) { - addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf(typeof(DS_REPL_NEIGHBOR))); + addr = IntPtr.Add(info, sizeof(int) * 2 + i * Marshal.SizeOf()); ReplicationNeighbor managedNeighbor = new ReplicationNeighbor(addr, _server, _nameTable); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs index 297691533afb67..99b639d6eb2627 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs @@ -48,11 +48,11 @@ internal void AddHelper(DS_REPL_PENDING_OPS operations, IntPtr info) // get the count int count = operations.cNumPendingOps; - IntPtr addr = (IntPtr)0; + IntPtr addr = 0; for (int i = 0; i < count; i++) { - addr = IntPtr.Add(info, Marshal.SizeOf(typeof(DS_REPL_PENDING_OPS)) + i * Marshal.SizeOf(typeof(DS_REPL_OP))); + addr = IntPtr.Add(info, Marshal.SizeOf() + i * Marshal.SizeOf()); ReplicationOperation managedOperation = new ReplicationOperation(addr, _server, _nameTable); Add(managedOperation); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs index 3c1f11fec589aa..6591d54f956ea2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs @@ -220,7 +220,7 @@ internal static unsafe void SetTrustedDomainInfoStatus(DirectoryContext context, } // reconstruct the unmanaged structure to set it back - newInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.Advapi32.TRUSTED_DOMAIN_INFORMATION_EX))); + newInfo = Marshal.AllocHGlobal(sizeof(Interop.Advapi32.TRUSTED_DOMAIN_INFORMATION_EX)); Marshal.StructureToPtr(domainInfo, newInfo, false); result = Interop.Advapi32.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, Interop.Advapi32.TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, newInfo); @@ -462,7 +462,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN Marshal.PtrToStructure(info, domainInfo); AuthData = new LSA_AUTH_INFORMATION(); - fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime))); + fileTime = Marshal.AllocHGlobal(Marshal.SizeOf()); Interop.Kernel32.GetSystemTimeAsFileTime(fileTime); // set the time @@ -477,7 +477,7 @@ internal static void CreateTrust(DirectoryContext sourceContext, string? sourceN AuthData.AuthInfo = unmanagedPassword; AuthData.AuthInfoLength = password.Length * 2; // sizeof(WCHAR) - unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION))); + unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf()); Marshal.StructureToPtr(AuthData, unmanagedAuthData, false); Interop.Advapi32.TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = default; @@ -616,7 +616,7 @@ internal static unsafe string UpdateTrust(DirectoryContext context, string? sour // change the attribute value properly AuthData = new LSA_AUTH_INFORMATION(); - fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime))); + fileTime = Marshal.AllocHGlobal(Marshal.SizeOf()); Interop.Kernel32.GetSystemTimeAsFileTime(fileTime); // set the time @@ -631,7 +631,7 @@ internal static unsafe string UpdateTrust(DirectoryContext context, string? sour AuthData.AuthInfo = unmanagedPassword; AuthData.AuthInfoLength = password.Length * 2; - unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION))); + unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf()); Marshal.StructureToPtr(AuthData, unmanagedAuthData, false); Interop.Advapi32.TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = default; @@ -743,7 +743,7 @@ internal static unsafe void UpdateTrustDirection(DirectoryContext context, strin // change the attribute value properly AuthData = new LSA_AUTH_INFORMATION(); - fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime))); + fileTime = Marshal.AllocHGlobal(Marshal.SizeOf()); Interop.Kernel32.GetSystemTimeAsFileTime(fileTime); // set the time @@ -758,7 +758,7 @@ internal static unsafe void UpdateTrustDirection(DirectoryContext context, strin AuthData.AuthInfo = unmanagedPassword; AuthData.AuthInfoLength = password.Length * 2; - unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION))); + unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf()); Marshal.StructureToPtr(AuthData, unmanagedAuthData, false); Interop.Advapi32.TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index dfa3f1f1e614b6..56412ca15b0279 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -2038,7 +2038,7 @@ internal static bool IsSamUser() } - internal static IntPtr GetCurrentUserSid() + internal static unsafe IntPtr GetCurrentUserSid() { SafeTokenHandle? tokenHandle = null; IntPtr pBuffer = IntPtr.Zero; @@ -2120,7 +2120,7 @@ out tokenHandle } // Retrieve the user's SID from the user info - global::Interop.TOKEN_USER tokenUser = (global::Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(global::Interop.TOKEN_USER))!; + Interop.TOKEN_USER tokenUser = *(Interop.TOKEN_USER*)pBuffer; IntPtr pUserSid = tokenUser.sidAndAttributes.Sid; // this is a reference into the NATIVE memory (into pBuffer) Debug.Assert(global::Interop.Advapi32.IsValidSid(pUserSid)); @@ -2147,7 +2147,7 @@ out tokenHandle } } - internal static IntPtr GetMachineDomainSid() + internal static unsafe IntPtr GetMachineDomainSid() { SafeLsaPolicyHandle? policyHandle = null; IntPtr pBuffer = IntPtr.Zero; @@ -2178,8 +2178,7 @@ internal static IntPtr GetMachineDomainSid() } Debug.Assert(pBuffer != IntPtr.Zero); - POLICY_ACCOUNT_DOMAIN_INFO info = (POLICY_ACCOUNT_DOMAIN_INFO) - Marshal.PtrToStructure(pBuffer, typeof(POLICY_ACCOUNT_DOMAIN_INFO))!; + POLICY_ACCOUNT_DOMAIN_INFO info = *(POLICY_ACCOUNT_DOMAIN_INFO*)pBuffer; Debug.Assert(global::Interop.Advapi32.IsValidSid(info.DomainSid)); @@ -2226,7 +2225,7 @@ internal static bool IsMachineDC(string? computerName) } DSROLE_PRIMARY_DOMAIN_INFO_BASIC dsRolePrimaryDomainInfo = - (DSROLE_PRIMARY_DOMAIN_INFO_BASIC)Marshal.PtrToStructure(dsRoleInfoPtr, typeof(DSROLE_PRIMARY_DOMAIN_INFO_BASIC))!; + Marshal.PtrToStructure(dsRoleInfoPtr)!; return (dsRolePrimaryDomainInfo.MachineRole == DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController || dsRolePrimaryDomainInfo.MachineRole == DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController); @@ -2238,15 +2237,14 @@ internal static bool IsMachineDC(string? computerName) } } - internal static SidType ClassifySID(IntPtr pSid) + internal static unsafe SidType ClassifySID(IntPtr pSid) { Debug.Assert(global::Interop.Advapi32.IsValidSid(pSid)); // Get the issuing authority and the first RID IntPtr pIdentAuth = global::Interop.Advapi32.GetSidIdentifierAuthority(pSid); - global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = - (global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY))!; + Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth = *(Interop.Advapi32.SID_IDENTIFIER_AUTHORITY*)pIdentAuth; IntPtr pRid = global::Interop.Advapi32.GetSidSubAuthority(pSid, 0); int rid = Marshal.ReadInt32(pRid); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs index 02f44bcb47654e..cdc2a4951234f4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs @@ -844,7 +844,7 @@ private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch ad ptrVLVContexToFree = vlvValue.contextID; Marshal.Copy(_vlv.DirectoryVirtualListViewContext._context, 0, vlvValue.contextID, vlvValue.contextIDlength); } - IntPtr vlvPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(AdsVLV))); + IntPtr vlvPtr = Marshal.AllocHGlobal(Marshal.SizeOf()); byte[] vlvBytes = new byte[Marshal.SizeOf(vlvValue)]; try { @@ -892,10 +892,10 @@ private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch ad } } - private static void DoSetSearchPrefs(UnsafeNativeMethods.IDirectorySearch adsSearch, AdsSearchPreferenceInfo[] prefs) + private static unsafe void DoSetSearchPrefs(UnsafeNativeMethods.IDirectorySearch adsSearch, AdsSearchPreferenceInfo[] prefs) { - int structSize = Marshal.SizeOf(typeof(AdsSearchPreferenceInfo)); - IntPtr ptr = Marshal.AllocHGlobal((IntPtr)(structSize * prefs.Length)); + int structSize = sizeof(AdsSearchPreferenceInfo); + IntPtr ptr = Marshal.AllocHGlobal(structSize * prefs.Length); try { IntPtr tempPtr = ptr; diff --git a/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs index e86b53d640d30f..9a9ad7ef521329 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs @@ -73,7 +73,7 @@ static bool TryConvertFromInvariantString( { Type? typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); MethodInfo? mi = typeDescriptorType?.GetMethod("ConvertFromInvariantString", BindingFlags.NonPublic | BindingFlags.Static); - Volatile.Write(ref s_convertFromInvariantString, mi == null ? new object() : mi.CreateDelegate(typeof(Func))); + Volatile.Write(ref s_convertFromInvariantString, mi == null ? new object() : mi.CreateDelegate>()); } if (!(s_convertFromInvariantString is Func convertFromInvariantString)) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index bcf5c1064e31c5..79bfc1a51f2a14 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -1516,8 +1516,8 @@ private static string GetDefaultDataContractNamespace(Type type) { string? clrNs = type.Namespace ?? string.Empty; string? ns = - GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()) ?? - GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); + GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes().ToArray()) ?? + GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes().ToArray()); if (ns == null) { @@ -2228,7 +2228,7 @@ private static bool IsMemberVisibleInSerializationModule(MemberInfo member) /// internal static bool IsAssemblyFriendOfSerialization(Assembly assembly) { - InternalsVisibleToAttribute[] internalsVisibleAttributes = (InternalsVisibleToAttribute[])assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute)); + InternalsVisibleToAttribute[] internalsVisibleAttributes = (InternalsVisibleToAttribute[])assembly.GetCustomAttributes(); foreach (InternalsVisibleToAttribute internalsVisibleAttribute in internalsVisibleAttributes) { string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index e9e2fdfe39bcaf..ba4c82f89539f6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -651,7 +651,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get MethodInfo getSetMemberValueDelegateWithTypeGenericMi = typeof(ReflectionXmlSerializationReaderHelper).GetMethod("GetSetMemberValueDelegateWithType", BindingFlags.Static | BindingFlags.Public)!; MethodInfo getSetMemberValueDelegateWithTypeMi = getSetMemberValueDelegateWithTypeGenericMi.MakeGenericMethod(o.GetType(), memberType); - var getSetMemberValueDelegateWithType = (Func)getSetMemberValueDelegateWithTypeMi.CreateDelegate(typeof(Func)); + var getSetMemberValueDelegateWithType = getSetMemberValueDelegateWithTypeMi.CreateDelegate>(); result = getSetMemberValueDelegateWithType(memberInfo); delegateCacheForType[memberName] = result; } @@ -2121,7 +2121,7 @@ public static SetMemberValueDelegate GetSetMemberValueDelegateWithType)setMethod.CreateDelegate(typeof(Action)); + setTypedDelegate = setMethod.CreateDelegate>(); } else if (memberInfo is FieldInfo fieldInfo) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs index 7c5ca1d4ca3502..9b2f875ddb6c1d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs @@ -229,7 +229,7 @@ public void Load(MethodInfo executeMethod, byte[] queryData, Type[]? earlyBoundT Delegate delExec = executeMethod is DynamicMethod dm ? dm.CreateDelegate(typeof(ExecuteDelegate)) - : executeMethod.CreateDelegate(typeof(ExecuteDelegate)); + : executeMethod.CreateDelegate(); _command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes)); OutputSettings = _command.StaticData.DefaultWriterSettings; diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.JSObject.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.JSObject.cs index bdaf228f6a7200..76f8ad8fd9c9d3 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.JSObject.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.JSObject.cs @@ -107,7 +107,7 @@ public unsafe void ToJS(JSObject?[] value) return; } slot.Length = value.Length; - int bytes = value.Length * Marshal.SizeOf(typeof(JSMarshalerArgument)); + int bytes = value.Length * sizeof(JSMarshalerArgument); slot.Type = MarshalerType.Array; slot.ElementType = MarshalerType.JSObject; JSMarshalerArgument* payload = (JSMarshalerArgument*)Marshal.AllocHGlobal(bytes); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.Object.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.Object.cs index 8a5105cbce828a..d9ed7cd4285851 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.Object.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.Object.cs @@ -373,7 +373,7 @@ public unsafe void ToJS(object?[] value) return; } slot.Length = value.Length; - int bytes = value.Length * Marshal.SizeOf(typeof(JSMarshalerArgument)); + int bytes = value.Length * sizeof(JSMarshalerArgument); slot.Type = MarshalerType.Array; JSMarshalerArgument* payload = (JSMarshalerArgument*)Marshal.AllocHGlobal(bytes); Unsafe.InitBlock(payload, 0, (uint)bytes); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.String.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.String.cs index 247aad1ec613a6..d0e2d9cb7f9f71 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.String.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Marshaling/JSMarshalerArgument.String.cs @@ -115,7 +115,7 @@ public unsafe void ToJS(string?[] value) return; } slot.Length = value.Length; - int bytes = value.Length * Marshal.SizeOf(typeof(JSMarshalerArgument)); + int bytes = value.Length * sizeof(JSMarshalerArgument); slot.Type = MarshalerType.Array; JSMarshalerArgument* payload = (JSMarshalerArgument*)Marshal.AllocHGlobal(bytes); Unsafe.InitBlock(payload, 0, (uint)bytes); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs index 3a5476f069eb26..10449accd7ce9c 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs @@ -709,7 +709,7 @@ private int Position(string? name) // A field on the type isn't found. See if the field has OptionalFieldAttribute. We only throw // when the assembly format is set appropriately. if (!_isSimpleAssembly && - _cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null) + _cache._memberInfos[i].GetCustomAttribute(inherit: false) == null) { Debug.Assert(_cache._memberNames != null); throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/LiteHash.Apple.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/LiteHash.Apple.cs index 57e63d8dc698c5..0b2fde720a20d4 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/LiteHash.Apple.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/LiteHash.Apple.cs @@ -64,7 +64,7 @@ internal LiteHash(PAL_HashAlgorithm algorithm) throw new PlatformNotSupportedException( SR.Format( SR.Cryptography_UnknownHashAlgorithm, - Enum.GetName(typeof(PAL_HashAlgorithm), algorithm))); + Enum.GetName(algorithm))); } if (_ctx.IsInvalid) @@ -159,7 +159,7 @@ internal LiteHmac(PAL_HashAlgorithm algorithm, ReadOnlySpan key, bool prei throw new PlatformNotSupportedException( SR.Format( SR.Cryptography_UnknownHashAlgorithm, - Enum.GetName(typeof(Interop.AppleCrypto.PAL_HashAlgorithm), algorithm))); + Enum.GetName(algorithm))); } if (_ctx.IsInvalid) diff --git a/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs b/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs index 6e39549fd0d604..d77919070c24df 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs @@ -582,9 +582,9 @@ private unsafe void ValidateSoundFile(string fileName) if (waveFormat == null) { int dw = ck.cksize; - if (dw < Marshal.SizeOf(typeof(Interop.WinMM.WAVEFORMATEX))) + if (dw < Marshal.SizeOf()) { - dw = Marshal.SizeOf(typeof(Interop.WinMM.WAVEFORMATEX)); + dw = Marshal.SizeOf(); } waveFormat = new Interop.WinMM.WAVEFORMATEX();