From: Shay Rojansky Date: Mon, 13 Jul 2020 08:49:23 +0000 (+0300) Subject: Nullability annotations for System.Data (#38810) X-Git-Tag: submit/tizen/20210909.063632~6761 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=8a94c7bc54a43d45c398025f07f70c99b658a4d8;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Nullability annotations for System.Data (#38810) Following ec73c56fb803b89f5e41b4c85c5be9f6bd1a5bab. A few corners have been left annotated because of dependencies. --- diff --git a/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs b/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs index f9a2ee0..c61589b 100644 --- a/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs +++ b/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs @@ -1,6 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable nullability as part of annotation System.Data.{Odbc,OleDb} +#nullable disable +#pragma warning disable CS8632 + using System.Collections; using System.Data.SqlTypes; using System.Diagnostics; @@ -471,7 +475,7 @@ namespace System.Data.Common return IndexOutOfRange(SR.Format(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); } - internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) => + internal static bool CompareInsensitiveInvariant(string? strvalue, string? strconst) => 0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase); internal static int DstCompare(string strA, string strB) => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions); diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs index 988a712..83f6b89 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs @@ -1,8 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated +#nullable disable +#pragma warning disable CS8632 + using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -90,8 +95,8 @@ namespace System.Data.Common } private readonly string _usersConnectionString; - private readonly Dictionary _parsetable; - internal readonly NameValuePair _keyChain; + private readonly Dictionary _parsetable; + internal readonly NameValuePair? _keyChain; internal readonly bool _hasPasswordKeyword; public string UsersConnectionString(bool hidePassword) => @@ -113,9 +118,10 @@ namespace System.Data.Common public bool ConvertValueToBoolean(string keyName, bool defaultValue) { - string value; + string? value; + // TODO: Is it possible for _parsetable to contain a null value here? If so there's a bug here, investigate. return _parsetable.TryGetValue(keyName, out value) ? - ConvertValueToBooleanInternal(keyName, value) : + ConvertValueToBooleanInternal(keyName, value!) : defaultValue; } @@ -143,7 +149,7 @@ namespace System.Data.Common (0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst)); [System.Diagnostics.Conditional("DEBUG")] - static partial void DebugTraceKeyValuePair(string keyname, string keyvalue, Dictionary synonyms); + static partial void DebugTraceKeyValuePair(string keyname, string? keyvalue, Dictionary? synonyms); private static string GetKeyName(StringBuilder buffer) { @@ -191,7 +197,7 @@ namespace System.Data.Common NullTermination, }; - internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue) + internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string? keyname, out string? keyvalue) { int startposition = currentPosition; @@ -396,7 +402,7 @@ namespace System.Data.Common } #pragma warning disable CA2249 // Consider using 'string.Contains' instead of 'string.IndexOf'. This file is built into libraries that don't have string.Contains(char). - private static bool IsValueValidInternal(string keyvalue) + private static bool IsValueValidInternal(string? keyvalue) { if (null != keyvalue) { @@ -410,7 +416,8 @@ namespace System.Data.Common return true; } - private static bool IsKeyNameValid(string keyname) + // TODO: Annotate with [NotNullWhen(true)] when annotating System.Data.{Odbc,OleDb} + private static bool IsKeyNameValid(string? keyname) { if (null != keyname) { @@ -426,7 +433,7 @@ namespace System.Data.Common #pragma warning restore CA2249 // Consider using 'string.Contains' instead of 'string.IndexOf' #if DEBUG - private static Dictionary SplitConnectionString(string connectionString, Dictionary synonyms, bool firstKey) + private static Dictionary SplitConnectionString(string connectionString, Dictionary? synonyms, bool firstKey) { var parsetable = new Dictionary(); Regex parser = (firstKey ? s_connectionStringRegexOdbc : s_connectionStringRegex); @@ -447,7 +454,7 @@ namespace System.Data.Common foreach (Capture keypair in match.Groups[KeyIndex].Captures) { string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant(); - string keyvalue = keyvalues[indexValue++].Value; + string? keyvalue = keyvalues[indexValue++].Value; if (0 < keyvalue.Length) { if (!firstKey) @@ -470,8 +477,8 @@ namespace System.Data.Common keyvalue = null; } DebugTraceKeyValuePair(keyname, keyvalue, synonyms); - string synonym; - string realkeyname = null != synonyms ? + string? synonym; + string? realkeyname = null != synonyms ? (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) : keyname; if (!IsKeyNameValid(realkeyname)) @@ -480,14 +487,14 @@ namespace System.Data.Common } if (!firstKey || !parsetable.ContainsKey(realkeyname)) { - parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) + parsetable[realkeyname] = keyvalue!; // last key-value pair wins (or first) } } } return parsetable; } - private static void ParseComparison(Dictionary parsetable, string connectionString, Dictionary synonyms, bool firstKey, Exception e) + private static void ParseComparison(Dictionary parsetable, string connectionString, Dictionary? synonyms, bool firstKey, Exception? e) { try { @@ -496,7 +503,7 @@ namespace System.Data.Common { string keyname = entry.Key; string value1 = entry.Value; - string value2; + string? value2; bool parsetableContainsKey = parsetable.TryGetValue(keyname, out value2); Debug.Assert(parsetableContainsKey, $"{nameof(ParseInternal)} code vs. regex mismatch keyname <{keyname}>"); Debug.Assert(value1 == value2, $"{nameof(ParseInternal)} code vs. regex mismatch keyvalue <{value1}> <{value2}>"); @@ -539,11 +546,11 @@ namespace System.Data.Common } #endif - private static NameValuePair ParseInternal(Dictionary parsetable, string connectionString, bool buildChain, Dictionary synonyms, bool firstKey) + private static NameValuePair? ParseInternal(Dictionary parsetable, string connectionString, bool buildChain, Dictionary? synonyms, bool firstKey) { Debug.Assert(null != connectionString, "null connectionstring"); StringBuilder buffer = new StringBuilder(); - NameValuePair localKeychain = null, keychain = null; + NameValuePair? localKeychain = null, keychain = null; #if DEBUG try { @@ -554,7 +561,7 @@ namespace System.Data.Common { int startPosition = nextStartPosition; - string keyname, keyvalue; + string? keyname, keyvalue; nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue); if (string.IsNullOrEmpty(keyname)) { @@ -566,8 +573,8 @@ namespace System.Data.Common Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname"); Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue"); #endif - string synonym; - string realkeyname = null != synonyms ? + string? synonym; + string? realkeyname = null != synonyms ? (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) : keyname; @@ -602,13 +609,13 @@ namespace System.Data.Common return keychain; } - internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) + internal NameValuePair? ReplacePasswordPwd(out string constr, bool fakePassword) { bool expanded = false; int copyPosition = 0; - NameValuePair head = null, tail = null, next = null; + NameValuePair? head = null, tail = null, next = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; null != current; current = current.Next) { if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name)) { diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs index 0e09b95..a2cd466 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionPoolKey.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated +#pragma warning disable CS8632 + namespace System.Data.Common { // DbConnectionPoolKey: Base class implementation of a key to connection pool groups @@ -37,14 +40,14 @@ namespace System.Data.Common } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null || obj.GetType() != typeof(DbConnectionPoolKey)) { return false; } - DbConnectionPoolKey key = obj as DbConnectionPoolKey; + DbConnectionPoolKey? key = obj as DbConnectionPoolKey; return (key != null && _connectionString == key._connectionString); } diff --git a/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs b/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs index 97f3609..3338928 100644 --- a/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs +++ b/src/libraries/Common/src/System/Data/Common/MultipartIdentifier.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - - +// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated +#pragma warning disable CS8632 //------------------------------------------------------------------------------ using System.Text; @@ -24,7 +24,7 @@ namespace System.Data.Common If a is the starting quote char then c would be the ending quote char otherwise if b is the starting quote char then d would be the ending quote character. */ - internal static string[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, string property, bool ThrowOnEmptyMultipartName) + internal static string?[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, string property, bool ThrowOnEmptyMultipartName) { return ParseMultipartIdentifier(name, leftQuote, rightQuote, '.', MaxParts, true, property, ThrowOnEmptyMultipartName); } @@ -47,7 +47,7 @@ namespace System.Data.Common * limit: number of names to parse out * removequote:to remove the quotes on the returned string */ - private static void IncrementStringCount(string name, string[] ary, ref int position, string property) + private static void IncrementStringCount(string name, string?[] ary, ref int position, string property) { ++position; int limit = ary.Length; @@ -63,7 +63,7 @@ namespace System.Data.Common return char.IsWhiteSpace(ch); } - internal static string[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, char separator, int limit, bool removequotes, string property, bool ThrowOnEmptyMultipartName) + internal static string?[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, char separator, int limit, bool removequotes, string property, bool ThrowOnEmptyMultipartName) { if (limit <= 0) { @@ -75,13 +75,13 @@ namespace System.Data.Common throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } - string[] parsedNames = new string[limit]; // return string array + string?[] parsedNames = new string?[limit]; // return string array int stringCount = 0; // index of current string in the buffer MPIState state = MPIState.MPI_Value; // Initialize the starting state StringBuilder sb = new StringBuilder(name.Length); // String buffer to hold the string being currently built, init the string builder so it will never be resized - StringBuilder whitespaceSB = null; // String buffer to hold whitespace used when parsing nonquoted strings 'a b . c d' = 'a b' and 'c d' - char rightQuoteChar = ' '; // Right quote character to use given the left quote character found. + StringBuilder? whitespaceSB = null; // String buffer to hold whitespace used when parsing nonquoted strings 'a b . c d' = 'a b' and 'c d' + char rightQuoteChar = ' '; // Right quote character to use given the left quote character found. for (int index = 0; index < name.Length; ++index) { char testchar = name[index]; @@ -182,7 +182,7 @@ namespace System.Data.Common } else { - whitespaceSB.Append(testchar); + whitespaceSB!.Append(testchar); } break; } diff --git a/src/libraries/Common/src/System/Data/Common/NameValuePair.cs b/src/libraries/Common/src/System/Data/Common/NameValuePair.cs index 6b78870..435b998 100644 --- a/src/libraries/Common/src/System/Data/Common/NameValuePair.cs +++ b/src/libraries/Common/src/System/Data/Common/NameValuePair.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Remove this after System.Data.{Odbc,OleDb} are null-annotated +#pragma warning disable CS8632 + using System.Diagnostics; namespace System.Data.Common @@ -8,11 +11,11 @@ namespace System.Data.Common internal sealed class NameValuePair { private readonly string _name; - private readonly string _value; + private readonly string? _value; private readonly int _length; - private NameValuePair _next; + private NameValuePair? _next; - internal NameValuePair(string name, string value, int length) + internal NameValuePair(string name, string? value, int length) { Debug.Assert(!string.IsNullOrEmpty(name), "empty keyname"); _name = name; @@ -30,9 +33,9 @@ namespace System.Data.Common } internal string Name => _name; - internal string Value => _value; + internal string? Value => _value; - internal NameValuePair Next + internal NameValuePair? Next { get { return _next; } set diff --git a/src/libraries/System.Data.Common/ref/System.Data.Common.cs b/src/libraries/System.Data.Common/ref/System.Data.Common.cs index 95f28aa..58feee8 100644 --- a/src/libraries/System.Data.Common/ref/System.Data.Common.cs +++ b/src/libraries/System.Data.Common/ref/System.Data.Common.cs @@ -49,12 +49,13 @@ namespace System.Data { internal Constraint() { } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public virtual string ConstraintName { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public System.Data.PropertyCollection ExtendedProperties { get { throw null; } } - public abstract System.Data.DataTable Table { get; } + public abstract System.Data.DataTable? Table { get; } [System.CLSCompliantAttribute(false)] - protected virtual System.Data.DataSet _DataSet { get { throw null; } } + protected virtual System.Data.DataSet? _DataSet { get { throw null; } } protected void CheckStateForProperty() { } protected internal void SetDataSet(System.Data.DataSet dataSet) { } public override string ToString() { throw null; } @@ -66,19 +67,19 @@ namespace System.Data public System.Data.Constraint this[int index] { get { throw null; } } public System.Data.Constraint this[string name] { get { throw null; } } protected override System.Collections.ArrayList List { get { throw null; } } - public event System.ComponentModel.CollectionChangeEventHandler CollectionChanged { add { } remove { } } + public event System.ComponentModel.CollectionChangeEventHandler? CollectionChanged { add { } remove { } } public void Add(System.Data.Constraint constraint) { } - public System.Data.Constraint Add(string name, System.Data.DataColumn column, bool primaryKey) { throw null; } - public System.Data.Constraint Add(string name, System.Data.DataColumn primaryKeyColumn, System.Data.DataColumn foreignKeyColumn) { throw null; } - public System.Data.Constraint Add(string name, System.Data.DataColumn[] columns, bool primaryKey) { throw null; } - public System.Data.Constraint Add(string name, System.Data.DataColumn[] primaryKeyColumns, System.Data.DataColumn[] foreignKeyColumns) { throw null; } - public void AddRange(System.Data.Constraint[] constraints) { } + public System.Data.Constraint Add(string? name, System.Data.DataColumn column, bool primaryKey) { throw null; } + public System.Data.Constraint Add(string? name, System.Data.DataColumn primaryKeyColumn, System.Data.DataColumn foreignKeyColumn) { throw null; } + public System.Data.Constraint Add(string? name, System.Data.DataColumn[] columns, bool primaryKey) { throw null; } + public System.Data.Constraint Add(string? name, System.Data.DataColumn[] primaryKeyColumns, System.Data.DataColumn[] foreignKeyColumns) { throw null; } + public void AddRange(System.Data.Constraint[]? constraints) { } public bool CanRemove(System.Data.Constraint constraint) { throw null; } public void Clear() { } - public bool Contains(string name) { throw null; } + public bool Contains(string? name) { throw null; } public void CopyTo(System.Data.Constraint[] array, int index) { } - public int IndexOf(System.Data.Constraint constraint) { throw null; } - public int IndexOf(string constraintName) { throw null; } + public int IndexOf(System.Data.Constraint? constraint) { throw null; } + public int IndexOf(string? constraintName) { throw null; } public void Remove(System.Data.Constraint constraint) { } public void Remove(string name) { } public void RemoveAt(int index) { } @@ -87,8 +88,8 @@ namespace System.Data { public ConstraintException() { } protected ConstraintException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public ConstraintException(string s) { } - public ConstraintException(string message, System.Exception innerException) { } + public ConstraintException(string? s) { } + public ConstraintException(string? message, System.Exception? innerException) { } } [System.ComponentModel.DefaultPropertyAttribute("ColumnName")] [System.ComponentModel.DesignTimeVisibleAttribute(false)] @@ -96,10 +97,10 @@ namespace System.Data public partial class DataColumn : System.ComponentModel.MarshalByValueComponent { public DataColumn() { } - public DataColumn(string columnName) { } - public DataColumn(string columnName, System.Type dataType) { } - public DataColumn(string columnName, System.Type dataType, string expr) { } - public DataColumn(string columnName, System.Type dataType, string expr, System.Data.MappingType type) { } + public DataColumn(string? columnName) { } + public DataColumn(string? columnName, System.Type dataType) { } + public DataColumn(string? columnName, System.Type dataType, string? expr) { } + public DataColumn(string? columnName, System.Type dataType, string? expr, System.Data.MappingType type) { } [System.ComponentModel.DefaultValueAttribute(true)] public bool AllowDBNull { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(false)] @@ -109,33 +110,38 @@ namespace System.Data public long AutoIncrementSeed { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((long)1)] public long AutoIncrementStep { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public string Caption { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.MappingType.Element)] public virtual System.Data.MappingType ColumnMapping { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] + [System.Diagnostics.CodeAnalysis.AllowNull] public string ColumnName { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.DataSetDateTime.UnspecifiedLocal)] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public System.Data.DataSetDateTime DateTimeMode { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] + [System.Diagnostics.CodeAnalysis.AllowNull] public string Expression { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public System.Data.PropertyCollection ExtendedProperties { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(-1)] public int MaxLength { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public string Namespace { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int Ordinal { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string Prefix { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(false)] public bool ReadOnly { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.DataTable Table { get { throw null; } } + public System.Data.DataTable? Table { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool Unique { get { throw null; } set { } } @@ -148,9 +154,9 @@ namespace System.Data } public partial class DataColumnChangeEventArgs : System.EventArgs { - public DataColumnChangeEventArgs(System.Data.DataRow row, System.Data.DataColumn column, object value) { } - public System.Data.DataColumn Column { get { throw null; } } - public object ProposedValue { get { throw null; } set { } } + public DataColumnChangeEventArgs(System.Data.DataRow row, System.Data.DataColumn? column, object? value) { } + public System.Data.DataColumn? Column { get { throw null; } } + public object? ProposedValue { get { throw null; } set { } } public System.Data.DataRow Row { get { throw null; } } } public delegate void DataColumnChangeEventHandler(object sender, System.Data.DataColumnChangeEventArgs e); @@ -159,21 +165,21 @@ namespace System.Data { internal DataColumnCollection() { } public System.Data.DataColumn this[int index] { get { throw null; } } - public System.Data.DataColumn this[string name] { get { throw null; } } + public System.Data.DataColumn? this[string name] { get { throw null; } } protected override System.Collections.ArrayList List { get { throw null; } } public event System.ComponentModel.CollectionChangeEventHandler CollectionChanged { add { } remove { } } public System.Data.DataColumn Add() { throw null; } public void Add(System.Data.DataColumn column) { } - public System.Data.DataColumn Add(string columnName) { throw null; } - public System.Data.DataColumn Add(string columnName, System.Type type) { throw null; } - public System.Data.DataColumn Add(string columnName, System.Type type, string expression) { throw null; } + public System.Data.DataColumn Add(string? columnName) { throw null; } + public System.Data.DataColumn Add(string? columnName, System.Type type) { throw null; } + public System.Data.DataColumn Add(string? columnName, System.Type type, string expression) { throw null; } public void AddRange(System.Data.DataColumn[] columns) { } - public bool CanRemove(System.Data.DataColumn column) { throw null; } + public bool CanRemove(System.Data.DataColumn? column) { throw null; } public void Clear() { } public bool Contains(string name) { throw null; } public void CopyTo(System.Data.DataColumn[] array, int index) { } - public int IndexOf(System.Data.DataColumn column) { throw null; } - public int IndexOf(string columnName) { throw null; } + public int IndexOf(System.Data.DataColumn? column) { throw null; } + public int IndexOf(string? columnName) { throw null; } public void Remove(System.Data.DataColumn column) { } public void Remove(string name) { } public void RemoveAt(int index) { } @@ -182,10 +188,9 @@ namespace System.Data { public DataException() { } protected DataException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public DataException(string s) { } - public DataException(string s, System.Exception innerException) { } + public DataException(string? s) { } + public DataException(string? s, System.Exception? innerException) { } } -#nullable enable public static partial class DataReaderExtensions { public static bool GetBoolean(this System.Data.Common.DbDataReader reader, string name) { throw null; } @@ -218,32 +223,32 @@ namespace System.Data public static bool IsDBNull(this System.Data.Common.DbDataReader reader, string name) { throw null; } public static System.Threading.Tasks.Task IsDBNullAsync(this System.Data.Common.DbDataReader reader, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } -#nullable disable [System.ComponentModel.DefaultPropertyAttribute("RelationName")] public partial class DataRelation { - public DataRelation(string relationName, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { } - public DataRelation(string relationName, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn, bool createConstraints) { } - public DataRelation(string relationName, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { } - public DataRelation(string relationName, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns, bool createConstraints) { } + public DataRelation(string? relationName, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { } + public DataRelation(string? relationName, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn, bool createConstraints) { } + public DataRelation(string? relationName, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { } + public DataRelation(string? relationName, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns, bool createConstraints) { } [System.ComponentModel.BrowsableAttribute(false)] - public DataRelation(string relationName, string parentTableName, string parentTableNamespace, string childTableName, string childTableNamespace, string[] parentColumnNames, string[] childColumnNames, bool nested) { } + public DataRelation(string relationName, string? parentTableName, string? parentTableNamespace, string? childTableName, string? childTableNamespace, string[]? parentColumnNames, string[]? childColumnNames, bool nested) { } [System.ComponentModel.BrowsableAttribute(false)] - public DataRelation(string relationName, string parentTableName, string childTableName, string[] parentColumnNames, string[] childColumnNames, bool nested) { } + public DataRelation(string relationName, string? parentTableName, string? childTableName, string[]? parentColumnNames, string[]? childColumnNames, bool nested) { } public virtual System.Data.DataColumn[] ChildColumns { get { throw null; } } - public virtual System.Data.ForeignKeyConstraint ChildKeyConstraint { get { throw null; } } + public virtual System.Data.ForeignKeyConstraint? ChildKeyConstraint { get { throw null; } } public virtual System.Data.DataTable ChildTable { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public virtual System.Data.DataSet DataSet { get { throw null; } } + public virtual System.Data.DataSet? DataSet { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Data.PropertyCollection ExtendedProperties { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(false)] public virtual bool Nested { get { throw null; } set { } } public virtual System.Data.DataColumn[] ParentColumns { get { throw null; } } - public virtual System.Data.UniqueConstraint ParentKeyConstraint { get { throw null; } } + public virtual System.Data.UniqueConstraint? ParentKeyConstraint { get { throw null; } } public virtual System.Data.DataTable ParentTable { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public virtual string RelationName { get { throw null; } set { } } protected void CheckStateForProperty() { } protected internal void OnPropertyChanging(System.ComponentModel.PropertyChangedEventArgs pcevent) { } @@ -256,24 +261,24 @@ namespace System.Data { protected DataRelationCollection() { } public abstract System.Data.DataRelation this[int index] { get; } - public abstract System.Data.DataRelation this[string name] { get; } - public event System.ComponentModel.CollectionChangeEventHandler CollectionChanged { add { } remove { } } + public abstract System.Data.DataRelation? this[string name] { get; } + public event System.ComponentModel.CollectionChangeEventHandler? CollectionChanged { add { } remove { } } public virtual System.Data.DataRelation Add(System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { throw null; } public virtual System.Data.DataRelation Add(System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { throw null; } public void Add(System.Data.DataRelation relation) { } - public virtual System.Data.DataRelation Add(string name, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { throw null; } - public virtual System.Data.DataRelation Add(string name, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn, bool createConstraints) { throw null; } - public virtual System.Data.DataRelation Add(string name, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { throw null; } - public virtual System.Data.DataRelation Add(string name, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns, bool createConstraints) { throw null; } + public virtual System.Data.DataRelation Add(string? name, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { throw null; } + public virtual System.Data.DataRelation Add(string? name, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn, bool createConstraints) { throw null; } + public virtual System.Data.DataRelation Add(string? name, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { throw null; } + public virtual System.Data.DataRelation Add(string? name, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns, bool createConstraints) { throw null; } protected virtual void AddCore(System.Data.DataRelation relation) { } - public virtual void AddRange(System.Data.DataRelation[] relations) { } - public virtual bool CanRemove(System.Data.DataRelation relation) { throw null; } + public virtual void AddRange(System.Data.DataRelation[]? relations) { } + public virtual bool CanRemove(System.Data.DataRelation? relation) { throw null; } public virtual void Clear() { } public virtual bool Contains(string name) { throw null; } public void CopyTo(System.Data.DataRelation[] array, int index) { } protected abstract System.Data.DataSet GetDataSet(); - public virtual int IndexOf(System.Data.DataRelation relation) { throw null; } - public virtual int IndexOf(string relationName) { throw null; } + public virtual int IndexOf(System.Data.DataRelation? relation) { throw null; } + public virtual int IndexOf(string? relationName) { throw null; } protected virtual void OnCollectionChanged(System.ComponentModel.CollectionChangeEventArgs ccevent) { } protected virtual void OnCollectionChanging(System.ComponentModel.CollectionChangeEventArgs ccevent) { } public void Remove(System.Data.DataRelation relation) { } @@ -285,13 +290,20 @@ namespace System.Data { protected internal DataRow(System.Data.DataRowBuilder builder) { } public bool HasErrors { get { throw null; } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[System.Data.DataColumn column] { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[System.Data.DataColumn column, System.Data.DataRowVersion version] { get { throw null; } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[int columnIndex] { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[int columnIndex, System.Data.DataRowVersion version] { get { throw null; } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[string columnName] { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[string columnName, System.Data.DataRowVersion version] { get { throw null; } } - public object[] ItemArray { get { throw null; } set { } } + public object?[] ItemArray { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public string RowError { get { throw null; } set { } } public System.Data.DataRowState RowState { get { throw null; } } public System.Data.DataTable Table { get { throw null; } } @@ -304,22 +316,22 @@ namespace System.Data public void Delete() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public void EndEdit() { } - public System.Data.DataRow[] GetChildRows(System.Data.DataRelation relation) { throw null; } - public System.Data.DataRow[] GetChildRows(System.Data.DataRelation relation, System.Data.DataRowVersion version) { throw null; } - public System.Data.DataRow[] GetChildRows(string relationName) { throw null; } - public System.Data.DataRow[] GetChildRows(string relationName, System.Data.DataRowVersion version) { throw null; } + public System.Data.DataRow[] GetChildRows(System.Data.DataRelation? relation) { throw null; } + public System.Data.DataRow[] GetChildRows(System.Data.DataRelation? relation, System.Data.DataRowVersion version) { throw null; } + public System.Data.DataRow[] GetChildRows(string? relationName) { throw null; } + public System.Data.DataRow[] GetChildRows(string? relationName, System.Data.DataRowVersion version) { throw null; } public string GetColumnError(System.Data.DataColumn column) { throw null; } public string GetColumnError(int columnIndex) { throw null; } public string GetColumnError(string columnName) { throw null; } public System.Data.DataColumn[] GetColumnsInError() { throw null; } - public System.Data.DataRow GetParentRow(System.Data.DataRelation relation) { throw null; } - public System.Data.DataRow GetParentRow(System.Data.DataRelation relation, System.Data.DataRowVersion version) { throw null; } - public System.Data.DataRow GetParentRow(string relationName) { throw null; } - public System.Data.DataRow GetParentRow(string relationName, System.Data.DataRowVersion version) { throw null; } - public System.Data.DataRow[] GetParentRows(System.Data.DataRelation relation) { throw null; } - public System.Data.DataRow[] GetParentRows(System.Data.DataRelation relation, System.Data.DataRowVersion version) { throw null; } - public System.Data.DataRow[] GetParentRows(string relationName) { throw null; } - public System.Data.DataRow[] GetParentRows(string relationName, System.Data.DataRowVersion version) { throw null; } + public System.Data.DataRow? GetParentRow(System.Data.DataRelation? relation) { throw null; } + public System.Data.DataRow? GetParentRow(System.Data.DataRelation? relation, System.Data.DataRowVersion version) { throw null; } + public System.Data.DataRow? GetParentRow(string? relationName) { throw null; } + public System.Data.DataRow? GetParentRow(string? relationName, System.Data.DataRowVersion version) { throw null; } + public System.Data.DataRow[] GetParentRows(System.Data.DataRelation? relation) { throw null; } + public System.Data.DataRow[] GetParentRows(System.Data.DataRelation? relation, System.Data.DataRowVersion version) { throw null; } + public System.Data.DataRow[] GetParentRows(string? relationName) { throw null; } + public System.Data.DataRow[] GetParentRows(string? relationName, System.Data.DataRowVersion version) { throw null; } public bool HasVersion(System.Data.DataRowVersion version) { throw null; } public bool IsNull(System.Data.DataColumn column) { throw null; } public bool IsNull(System.Data.DataColumn column, System.Data.DataRowVersion version) { throw null; } @@ -327,13 +339,13 @@ namespace System.Data public bool IsNull(string columnName) { throw null; } public void RejectChanges() { } public void SetAdded() { } - public void SetColumnError(System.Data.DataColumn column, string error) { } - public void SetColumnError(int columnIndex, string error) { } - public void SetColumnError(string columnName, string error) { } + public void SetColumnError(System.Data.DataColumn column, string? error) { } + public void SetColumnError(int columnIndex, string? error) { } + public void SetColumnError(string columnName, string? error) { } public void SetModified() { } protected void SetNull(System.Data.DataColumn column) { } - public void SetParentRow(System.Data.DataRow parentRow) { } - public void SetParentRow(System.Data.DataRow parentRow, System.Data.DataRelation relation) { } + public void SetParentRow(System.Data.DataRow? parentRow) { } + public void SetParentRow(System.Data.DataRow? parentRow, System.Data.DataRelation? relation) { } } [System.FlagsAttribute] public enum DataRowAction @@ -364,16 +376,16 @@ namespace System.Data public override int Count { get { throw null; } } public System.Data.DataRow this[int index] { get { throw null; } } public void Add(System.Data.DataRow row) { } - public System.Data.DataRow Add(params object[] values) { throw null; } + public System.Data.DataRow Add(params object?[] values) { throw null; } public void Clear() { } public bool Contains(object key) { throw null; } public bool Contains(object[] keys) { throw null; } public override void CopyTo(System.Array ar, int index) { } public void CopyTo(System.Data.DataRow[] array, int index) { } - public System.Data.DataRow Find(object key) { throw null; } - public System.Data.DataRow Find(object[] keys) { throw null; } + public System.Data.DataRow? Find(object? key) { throw null; } + public System.Data.DataRow? Find(object?[] keys) { throw null; } public override System.Collections.IEnumerator GetEnumerator() { throw null; } - public int IndexOf(System.Data.DataRow row) { throw null; } + public int IndexOf(System.Data.DataRow? row) { throw null; } public void InsertAt(System.Data.DataRow row, int pos) { } public void Remove(System.Data.DataRow row) { } public void RemoveAt(int index) { } @@ -386,20 +398,26 @@ namespace System.Data { internal DataRowComparer() { } public static System.Data.DataRowComparer Default { get { throw null; } } - public bool Equals(TRow leftRow, TRow rightRow) { throw null; } + public bool Equals(TRow? leftRow, TRow? rightRow) { throw null; } public int GetHashCode(TRow row) { throw null; } } public static partial class DataRowExtensions { + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static T Field(this System.Data.DataRow row, System.Data.DataColumn column) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static T Field(this System.Data.DataRow row, System.Data.DataColumn column, System.Data.DataRowVersion version) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static T Field(this System.Data.DataRow row, int columnIndex) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static T Field(this System.Data.DataRow row, int columnIndex, System.Data.DataRowVersion version) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static T Field(this System.Data.DataRow row, string columnName) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static T Field(this System.Data.DataRow row, string columnName, System.Data.DataRowVersion version) { throw null; } - public static void SetField(this System.Data.DataRow row, System.Data.DataColumn column, T value) { } - public static void SetField(this System.Data.DataRow row, int columnIndex, T value) { } - public static void SetField(this System.Data.DataRow row, string columnName, T value) { } + public static void SetField(this System.Data.DataRow row, System.Data.DataColumn column, [System.Diagnostics.CodeAnalysis.AllowNull] T value) { } + public static void SetField(this System.Data.DataRow row, int columnIndex, [System.Diagnostics.CodeAnalysis.AllowNull] T value) { } + public static void SetField(this System.Data.DataRow row, string columnName, [System.Diagnostics.CodeAnalysis.AllowNull] T value) { } } [System.FlagsAttribute] public enum DataRowState @@ -423,13 +441,17 @@ namespace System.Data public System.Data.DataView DataView { get { throw null; } } public bool IsEdit { get { throw null; } } public bool IsNew { get { throw null; } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[int ndx] { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public object this[string property] { get { throw null; } set { } } public System.Data.DataRow Row { get { throw null; } } public System.Data.DataRowVersion RowVersion { get { throw null; } } +#nullable disable string System.ComponentModel.IDataErrorInfo.Error { get { throw null; } } string System.ComponentModel.IDataErrorInfo.this[string colName] { get { throw null; } } - public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } +#nullable enable + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged { add { } remove { } } public void BeginEdit() { } public void CancelEdit() { } public System.Data.DataView CreateChildView(System.Data.DataRelation relation) { throw null; } @@ -438,8 +460,9 @@ namespace System.Data public System.Data.DataView CreateChildView(string relationName, bool followParent) { throw null; } public void Delete() { } public void EndEdit() { } - public override bool Equals(object other) { throw null; } + public override bool Equals(object? other) { throw null; } public override int GetHashCode() { throw null; } +#nullable disable System.ComponentModel.AttributeCollection System.ComponentModel.ICustomTypeDescriptor.GetAttributes() { throw null; } string System.ComponentModel.ICustomTypeDescriptor.GetClassName() { throw null; } string System.ComponentModel.ICustomTypeDescriptor.GetComponentName() { throw null; } @@ -452,6 +475,7 @@ namespace System.Data System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { throw null; } System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties(System.Attribute[] attributes) { throw null; } object System.ComponentModel.ICustomTypeDescriptor.GetPropertyOwner(System.ComponentModel.PropertyDescriptor pd) { throw null; } +#nullable enable } [System.ComponentModel.DefaultPropertyAttribute("DataSetName")] [System.Xml.Serialization.XmlRootAttribute("DataSet")] @@ -478,8 +502,10 @@ namespace System.Data public bool IsInitialized { get { throw null; } } public System.Globalization.CultureInfo Locale { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string Namespace { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string Prefix { get { throw null; } set { } } [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Data.DataRelationCollection Relations { get { throw null; } } @@ -488,14 +514,16 @@ namespace System.Data [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.Data.SchemaSerializationMode SchemaSerializationMode { get { throw null; } set { } } +#nullable disable [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public override System.ComponentModel.ISite Site { get { throw null; } set { } } bool System.ComponentModel.IListSource.ContainsListCollection { get { throw null; } } +#nullable enable [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Data.DataTableCollection Tables { get { throw null; } } - public event System.EventHandler Initialized { add { } remove { } } - public event System.Data.MergeFailedEventHandler MergeFailed { add { } remove { } } + public event System.EventHandler? Initialized { add { } remove { } } + public event System.Data.MergeFailedEventHandler? MergeFailed { add { } remove { } } public void AcceptChanges() { } public void BeginInit() { } public void Clear() { } @@ -506,24 +534,24 @@ namespace System.Data protected System.Data.SchemaSerializationMode DetermineSchemaSerializationMode(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { throw null; } protected System.Data.SchemaSerializationMode DetermineSchemaSerializationMode(System.Xml.XmlReader reader) { throw null; } public void EndInit() { } - public System.Data.DataSet GetChanges() { throw null; } - public System.Data.DataSet GetChanges(System.Data.DataRowState rowStates) { throw null; } - public static System.Xml.Schema.XmlSchemaComplexType GetDataSetSchema(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } + public System.Data.DataSet? GetChanges() { throw null; } + public System.Data.DataSet? GetChanges(System.Data.DataRowState rowStates) { throw null; } + public static System.Xml.Schema.XmlSchemaComplexType GetDataSetSchema(System.Xml.Schema.XmlSchemaSet? schemaSet) { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - protected virtual System.Xml.Schema.XmlSchema GetSchemaSerializable() { throw null; } + protected virtual System.Xml.Schema.XmlSchema? GetSchemaSerializable() { throw null; } protected void GetSerializationData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public string GetXml() { throw null; } public string GetXmlSchema() { throw null; } public bool HasChanges() { throw null; } public bool HasChanges(System.Data.DataRowState rowStates) { throw null; } - public void InferXmlSchema(System.IO.Stream stream, string[] nsArray) { } - public void InferXmlSchema(System.IO.TextReader reader, string[] nsArray) { } - public void InferXmlSchema(string fileName, string[] nsArray) { } - public void InferXmlSchema(System.Xml.XmlReader reader, string[] nsArray) { } + public void InferXmlSchema(System.IO.Stream? stream, string[]? nsArray) { } + public void InferXmlSchema(System.IO.TextReader? reader, string[]? nsArray) { } + public void InferXmlSchema(string fileName, string[]? nsArray) { } + public void InferXmlSchema(System.Xml.XmlReader? reader, string[]? nsArray) { } protected virtual void InitializeDerivedDataSet() { } protected bool IsBinarySerialized(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { throw null; } public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, params System.Data.DataTable[] tables) { } - public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler, params System.Data.DataTable[] tables) { } + public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler, params System.Data.DataTable[] tables) { } public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, params string[] tables) { } public void Merge(System.Data.DataRow[] rows) { } public void Merge(System.Data.DataRow[] rows, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction) { } @@ -536,43 +564,45 @@ namespace System.Data protected virtual void OnRemoveRelation(System.Data.DataRelation relation) { } protected internal virtual void OnRemoveTable(System.Data.DataTable table) { } protected internal void RaisePropertyChanging(string name) { } - public System.Data.XmlReadMode ReadXml(System.IO.Stream stream) { throw null; } - public System.Data.XmlReadMode ReadXml(System.IO.Stream stream, System.Data.XmlReadMode mode) { throw null; } - public System.Data.XmlReadMode ReadXml(System.IO.TextReader reader) { throw null; } - public System.Data.XmlReadMode ReadXml(System.IO.TextReader reader, System.Data.XmlReadMode mode) { throw null; } + public System.Data.XmlReadMode ReadXml(System.IO.Stream? stream) { throw null; } + public System.Data.XmlReadMode ReadXml(System.IO.Stream? stream, System.Data.XmlReadMode mode) { throw null; } + public System.Data.XmlReadMode ReadXml(System.IO.TextReader? reader) { throw null; } + public System.Data.XmlReadMode ReadXml(System.IO.TextReader? reader, System.Data.XmlReadMode mode) { throw null; } public System.Data.XmlReadMode ReadXml(string fileName) { throw null; } public System.Data.XmlReadMode ReadXml(string fileName, System.Data.XmlReadMode mode) { throw null; } - public System.Data.XmlReadMode ReadXml(System.Xml.XmlReader reader) { throw null; } - public System.Data.XmlReadMode ReadXml(System.Xml.XmlReader reader, System.Data.XmlReadMode mode) { throw null; } - public void ReadXmlSchema(System.IO.Stream stream) { } - public void ReadXmlSchema(System.IO.TextReader reader) { } + public System.Data.XmlReadMode ReadXml(System.Xml.XmlReader? reader) { throw null; } + public System.Data.XmlReadMode ReadXml(System.Xml.XmlReader? reader, System.Data.XmlReadMode mode) { throw null; } + public void ReadXmlSchema(System.IO.Stream? stream) { } + public void ReadXmlSchema(System.IO.TextReader? reader) { } public void ReadXmlSchema(string fileName) { } - public void ReadXmlSchema(System.Xml.XmlReader reader) { } + public void ReadXmlSchema(System.Xml.XmlReader? reader) { } protected virtual void ReadXmlSerializable(System.Xml.XmlReader reader) { } public virtual void RejectChanges() { } public virtual void Reset() { } protected virtual bool ShouldSerializeRelations() { throw null; } protected virtual bool ShouldSerializeTables() { throw null; } +#nullable disable System.Collections.IList System.ComponentModel.IListSource.GetList() { throw null; } System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } - public void WriteXml(System.IO.Stream stream) { } - public void WriteXml(System.IO.Stream stream, System.Data.XmlWriteMode mode) { } - public void WriteXml(System.IO.TextWriter writer) { } - public void WriteXml(System.IO.TextWriter writer, System.Data.XmlWriteMode mode) { } +#nullable enable + public void WriteXml(System.IO.Stream? stream) { } + public void WriteXml(System.IO.Stream? stream, System.Data.XmlWriteMode mode) { } + public void WriteXml(System.IO.TextWriter? writer) { } + public void WriteXml(System.IO.TextWriter? writer, System.Data.XmlWriteMode mode) { } public void WriteXml(string fileName) { } public void WriteXml(string fileName, System.Data.XmlWriteMode mode) { } - public void WriteXml(System.Xml.XmlWriter writer) { } - public void WriteXml(System.Xml.XmlWriter writer, System.Data.XmlWriteMode mode) { } - public void WriteXmlSchema(System.IO.Stream stream) { } - public void WriteXmlSchema(System.IO.Stream stream, System.Converter multipleTargetConverter) { } - public void WriteXmlSchema(System.IO.TextWriter writer) { } - public void WriteXmlSchema(System.IO.TextWriter writer, System.Converter multipleTargetConverter) { } + public void WriteXml(System.Xml.XmlWriter? writer) { } + public void WriteXml(System.Xml.XmlWriter? writer, System.Data.XmlWriteMode mode) { } + public void WriteXmlSchema(System.IO.Stream? stream) { } + public void WriteXmlSchema(System.IO.Stream? stream, System.Converter? multipleTargetConverter) { } + public void WriteXmlSchema(System.IO.TextWriter? writer) { } + public void WriteXmlSchema(System.IO.TextWriter? writer, System.Converter? multipleTargetConverter) { } public void WriteXmlSchema(string fileName) { } - public void WriteXmlSchema(string fileName, System.Converter multipleTargetConverter) { } - public void WriteXmlSchema(System.Xml.XmlWriter writer) { } - public void WriteXmlSchema(System.Xml.XmlWriter writer, System.Converter multipleTargetConverter) { } + public void WriteXmlSchema(string fileName, System.Converter? multipleTargetConverter) { } + public void WriteXmlSchema(System.Xml.XmlWriter? writer) { } + public void WriteXmlSchema(System.Xml.XmlWriter? writer, System.Converter? multipleTargetConverter) { } } public enum DataSetDateTime { @@ -599,8 +629,8 @@ namespace System.Data protected internal bool fInitInProgress; public DataTable() { } protected DataTable(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public DataTable(string tableName) { } - public DataTable(string tableName, string tableNamespace) { } + public DataTable(string? tableName) { } + public DataTable(string? tableName, string? tableNamespace) { } public bool CaseSensitive { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] @@ -611,10 +641,11 @@ namespace System.Data public System.Data.ConstraintCollection Constraints { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.DataSet DataSet { get { throw null; } } + public System.Data.DataSet? DataSet { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Data.DataView DefaultView { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string DisplayExpression { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public System.Data.PropertyCollection ExtendedProperties { get { throw null; } } @@ -630,6 +661,7 @@ namespace System.Data [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.Data.DataRelationCollection ParentRelations { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string Prefix { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.SerializationFormat.Xml)] public System.Data.SerializationFormat RemotingFormat { get { throw null; } set { } } @@ -637,45 +669,48 @@ namespace System.Data public System.Data.DataRowCollection Rows { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] +#nullable disable public override System.ComponentModel.ISite Site { get { throw null; } set { } } +#nullable enable bool System.ComponentModel.IListSource.ContainsListCollection { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] + [System.Diagnostics.CodeAnalysis.AllowNull] public string TableName { get { throw null; } set { } } - public event System.Data.DataColumnChangeEventHandler ColumnChanged { add { } remove { } } - public event System.Data.DataColumnChangeEventHandler ColumnChanging { add { } remove { } } - public event System.EventHandler Initialized { add { } remove { } } - public event System.Data.DataRowChangeEventHandler RowChanged { add { } remove { } } - public event System.Data.DataRowChangeEventHandler RowChanging { add { } remove { } } - public event System.Data.DataRowChangeEventHandler RowDeleted { add { } remove { } } - public event System.Data.DataRowChangeEventHandler RowDeleting { add { } remove { } } - public event System.Data.DataTableClearEventHandler TableCleared { add { } remove { } } - public event System.Data.DataTableClearEventHandler TableClearing { add { } remove { } } - public event System.Data.DataTableNewRowEventHandler TableNewRow { add { } remove { } } + public event System.Data.DataColumnChangeEventHandler? ColumnChanged { add { } remove { } } + public event System.Data.DataColumnChangeEventHandler? ColumnChanging { add { } remove { } } + public event System.EventHandler? Initialized { add { } remove { } } + public event System.Data.DataRowChangeEventHandler? RowChanged { add { } remove { } } + public event System.Data.DataRowChangeEventHandler? RowChanging { add { } remove { } } + public event System.Data.DataRowChangeEventHandler? RowDeleted { add { } remove { } } + public event System.Data.DataRowChangeEventHandler? RowDeleting { add { } remove { } } + public event System.Data.DataTableClearEventHandler? TableCleared { add { } remove { } } + public event System.Data.DataTableClearEventHandler? TableClearing { add { } remove { } } + public event System.Data.DataTableNewRowEventHandler? TableNewRow { add { } remove { } } public void AcceptChanges() { } public virtual void BeginInit() { } public void BeginLoadData() { } public void Clear() { } public virtual System.Data.DataTable Clone() { throw null; } - public object Compute(string expression, string filter) { throw null; } + public object Compute(string? expression, string? filter) { throw null; } public System.Data.DataTable Copy() { throw null; } public System.Data.DataTableReader CreateDataReader() { throw null; } protected virtual System.Data.DataTable CreateInstance() { throw null; } public virtual void EndInit() { } public void EndLoadData() { } - public System.Data.DataTable GetChanges() { throw null; } - public System.Data.DataTable GetChanges(System.Data.DataRowState rowStates) { throw null; } - public static System.Xml.Schema.XmlSchemaComplexType GetDataTableSchema(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } + public System.Data.DataTable? GetChanges() { throw null; } + public System.Data.DataTable? GetChanges(System.Data.DataRowState rowStates) { throw null; } + public static System.Xml.Schema.XmlSchemaComplexType GetDataTableSchema(System.Xml.Schema.XmlSchemaSet? schemaSet) { throw null; } public System.Data.DataRow[] GetErrors() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual System.Type GetRowType() { throw null; } protected virtual System.Xml.Schema.XmlSchema GetSchema() { throw null; } - public void ImportRow(System.Data.DataRow row) { } + public void ImportRow(System.Data.DataRow? row) { } public void Load(System.Data.IDataReader reader) { } public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption) { } - public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler) { } - public System.Data.DataRow LoadDataRow(object[] values, bool fAcceptChanges) { throw null; } - public System.Data.DataRow LoadDataRow(object[] values, System.Data.LoadOption loadOption) { throw null; } + public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler) { } + public System.Data.DataRow LoadDataRow(object?[] values, bool fAcceptChanges) { throw null; } + public System.Data.DataRow LoadDataRow(object?[] values, System.Data.LoadOption loadOption) { throw null; } public void Merge(System.Data.DataTable table) { } public void Merge(System.Data.DataTable table, bool preserveChanges) { } public void Merge(System.Data.DataTable table, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction) { } @@ -693,50 +728,52 @@ namespace System.Data protected virtual void OnTableCleared(System.Data.DataTableClearEventArgs e) { } protected virtual void OnTableClearing(System.Data.DataTableClearEventArgs e) { } protected virtual void OnTableNewRow(System.Data.DataTableNewRowEventArgs e) { } - public System.Data.XmlReadMode ReadXml(System.IO.Stream stream) { throw null; } - public System.Data.XmlReadMode ReadXml(System.IO.TextReader reader) { throw null; } + public System.Data.XmlReadMode ReadXml(System.IO.Stream? stream) { throw null; } + public System.Data.XmlReadMode ReadXml(System.IO.TextReader? reader) { throw null; } public System.Data.XmlReadMode ReadXml(string fileName) { throw null; } - public System.Data.XmlReadMode ReadXml(System.Xml.XmlReader reader) { throw null; } - public void ReadXmlSchema(System.IO.Stream stream) { } - public void ReadXmlSchema(System.IO.TextReader reader) { } + public System.Data.XmlReadMode ReadXml(System.Xml.XmlReader? reader) { throw null; } + public void ReadXmlSchema(System.IO.Stream? stream) { } + public void ReadXmlSchema(System.IO.TextReader? reader) { } public void ReadXmlSchema(string fileName) { } - public void ReadXmlSchema(System.Xml.XmlReader reader) { } - protected virtual void ReadXmlSerializable(System.Xml.XmlReader reader) { } + public void ReadXmlSchema(System.Xml.XmlReader? reader) { } + protected virtual void ReadXmlSerializable(System.Xml.XmlReader? reader) { } public void RejectChanges() { } public virtual void Reset() { } public System.Data.DataRow[] Select() { throw null; } - public System.Data.DataRow[] Select(string filterExpression) { throw null; } - public System.Data.DataRow[] Select(string filterExpression, string sort) { throw null; } - public System.Data.DataRow[] Select(string filterExpression, string sort, System.Data.DataViewRowState recordStates) { throw null; } + public System.Data.DataRow[] Select(string? filterExpression) { throw null; } + public System.Data.DataRow[] Select(string? filterExpression, string? sort) { throw null; } + public System.Data.DataRow[] Select(string? filterExpression, string? sort, System.Data.DataViewRowState recordStates) { throw null; } System.Collections.IList System.ComponentModel.IListSource.GetList() { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } +#nullable disable void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } +#nullable enable public override string ToString() { throw null; } - public void WriteXml(System.IO.Stream stream) { } - public void WriteXml(System.IO.Stream stream, bool writeHierarchy) { } - public void WriteXml(System.IO.Stream stream, System.Data.XmlWriteMode mode) { } - public void WriteXml(System.IO.Stream stream, System.Data.XmlWriteMode mode, bool writeHierarchy) { } - public void WriteXml(System.IO.TextWriter writer) { } - public void WriteXml(System.IO.TextWriter writer, bool writeHierarchy) { } - public void WriteXml(System.IO.TextWriter writer, System.Data.XmlWriteMode mode) { } - public void WriteXml(System.IO.TextWriter writer, System.Data.XmlWriteMode mode, bool writeHierarchy) { } + public void WriteXml(System.IO.Stream? stream) { } + public void WriteXml(System.IO.Stream? stream, bool writeHierarchy) { } + public void WriteXml(System.IO.Stream? stream, System.Data.XmlWriteMode mode) { } + public void WriteXml(System.IO.Stream? stream, System.Data.XmlWriteMode mode, bool writeHierarchy) { } + public void WriteXml(System.IO.TextWriter? writer) { } + public void WriteXml(System.IO.TextWriter? writer, bool writeHierarchy) { } + public void WriteXml(System.IO.TextWriter? writer, System.Data.XmlWriteMode mode) { } + public void WriteXml(System.IO.TextWriter? writer, System.Data.XmlWriteMode mode, bool writeHierarchy) { } public void WriteXml(string fileName) { } public void WriteXml(string fileName, bool writeHierarchy) { } public void WriteXml(string fileName, System.Data.XmlWriteMode mode) { } public void WriteXml(string fileName, System.Data.XmlWriteMode mode, bool writeHierarchy) { } - public void WriteXml(System.Xml.XmlWriter writer) { } - public void WriteXml(System.Xml.XmlWriter writer, bool writeHierarchy) { } - public void WriteXml(System.Xml.XmlWriter writer, System.Data.XmlWriteMode mode) { } - public void WriteXml(System.Xml.XmlWriter writer, System.Data.XmlWriteMode mode, bool writeHierarchy) { } - public void WriteXmlSchema(System.IO.Stream stream) { } - public void WriteXmlSchema(System.IO.Stream stream, bool writeHierarchy) { } - public void WriteXmlSchema(System.IO.TextWriter writer) { } - public void WriteXmlSchema(System.IO.TextWriter writer, bool writeHierarchy) { } + public void WriteXml(System.Xml.XmlWriter? writer) { } + public void WriteXml(System.Xml.XmlWriter? writer, bool writeHierarchy) { } + public void WriteXml(System.Xml.XmlWriter? writer, System.Data.XmlWriteMode mode) { } + public void WriteXml(System.Xml.XmlWriter? writer, System.Data.XmlWriteMode mode, bool writeHierarchy) { } + public void WriteXmlSchema(System.IO.Stream? stream) { } + public void WriteXmlSchema(System.IO.Stream? stream, bool writeHierarchy) { } + public void WriteXmlSchema(System.IO.TextWriter? writer) { } + public void WriteXmlSchema(System.IO.TextWriter? writer, bool writeHierarchy) { } public void WriteXmlSchema(string fileName) { } public void WriteXmlSchema(string fileName, bool writeHierarchy) { } - public void WriteXmlSchema(System.Xml.XmlWriter writer) { } - public void WriteXmlSchema(System.Xml.XmlWriter writer, bool writeHierarchy) { } + public void WriteXmlSchema(System.Xml.XmlWriter? writer) { } + public void WriteXmlSchema(System.Xml.XmlWriter? writer, bool writeHierarchy) { } } public sealed partial class DataTableClearEventArgs : System.EventArgs { @@ -752,23 +789,23 @@ namespace System.Data { internal DataTableCollection() { } public System.Data.DataTable this[int index] { get { throw null; } } - public System.Data.DataTable this[string name] { get { throw null; } } - public System.Data.DataTable this[string name, string tableNamespace] { get { throw null; } } + public System.Data.DataTable? this[string? name] { get { throw null; } } + public System.Data.DataTable? this[string? name, string tableNamespace] { get { throw null; } } protected override System.Collections.ArrayList List { get { throw null; } } - public event System.ComponentModel.CollectionChangeEventHandler CollectionChanged { add { } remove { } } - public event System.ComponentModel.CollectionChangeEventHandler CollectionChanging { add { } remove { } } + public event System.ComponentModel.CollectionChangeEventHandler? CollectionChanged { add { } remove { } } + public event System.ComponentModel.CollectionChangeEventHandler? CollectionChanging { add { } remove { } } public System.Data.DataTable Add() { throw null; } public void Add(System.Data.DataTable table) { } - public System.Data.DataTable Add(string name) { throw null; } - public System.Data.DataTable Add(string name, string tableNamespace) { throw null; } - public void AddRange(System.Data.DataTable[] tables) { } - public bool CanRemove(System.Data.DataTable table) { throw null; } + public System.Data.DataTable Add(string? name) { throw null; } + public System.Data.DataTable Add(string? name, string? tableNamespace) { throw null; } + public void AddRange(System.Data.DataTable?[]? tables) { } + public bool CanRemove(System.Data.DataTable? table) { throw null; } public void Clear() { } - public bool Contains(string name) { throw null; } + public bool Contains(string? name) { throw null; } public bool Contains(string name, string tableNamespace) { throw null; } public void CopyTo(System.Data.DataTable[] array, int index) { } public int IndexOf(System.Data.DataTable table) { throw null; } - public int IndexOf(string tableName) { throw null; } + public int IndexOf(string? tableName) { throw null; } public int IndexOf(string tableName, string tableNamespace) { throw null; } public void Remove(System.Data.DataTable table) { } public void Remove(string name) { } @@ -782,7 +819,7 @@ namespace System.Data public static System.Data.EnumerableRowCollection AsEnumerable(this System.Data.DataTable source) { throw null; } public static System.Data.DataTable CopyToDataTable(this System.Collections.Generic.IEnumerable source) where T : System.Data.DataRow { throw null; } public static void CopyToDataTable(this System.Collections.Generic.IEnumerable source, System.Data.DataTable table, System.Data.LoadOption options) where T : System.Data.DataRow { } - public static void CopyToDataTable(this System.Collections.Generic.IEnumerable source, System.Data.DataTable table, System.Data.LoadOption options, System.Data.FillErrorEventHandler errorHandler) where T : System.Data.DataRow { } + public static void CopyToDataTable(this System.Collections.Generic.IEnumerable source, System.Data.DataTable table, System.Data.LoadOption options, System.Data.FillErrorEventHandler? errorHandler) where T : System.Data.DataRow { } } public sealed partial class DataTableNewRowEventArgs : System.EventArgs { @@ -804,9 +841,9 @@ namespace System.Data public override void Close() { } public override bool GetBoolean(int ordinal) { throw null; } public override byte GetByte(int ordinal) { throw null; } - public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; } + public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int bufferIndex, int length) { throw null; } public override char GetChar(int ordinal) { throw null; } - public override long GetChars(int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; } + public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int bufferIndex, int length) { throw null; } public override string GetDataTypeName(int ordinal) { throw null; } public override System.DateTime GetDateTime(int ordinal) { throw null; } public override decimal GetDecimal(int ordinal) { throw null; } @@ -836,8 +873,8 @@ namespace System.Data public partial class DataView : System.ComponentModel.MarshalByValueComponent, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList, System.ComponentModel.IBindingList, System.ComponentModel.IBindingListView, System.ComponentModel.ISupportInitialize, System.ComponentModel.ISupportInitializeNotification, System.ComponentModel.ITypedList { public DataView() { } - public DataView(System.Data.DataTable table) { } - public DataView(System.Data.DataTable table, string RowFilter, string Sort, System.Data.DataViewRowState RowState) { } + public DataView(System.Data.DataTable? table) { } + public DataView(System.Data.DataTable table, string? RowFilter, string? Sort, System.Data.DataViewRowState RowState) { } [System.ComponentModel.DefaultValueAttribute(true)] public bool AllowDelete { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(true)] @@ -850,23 +887,24 @@ namespace System.Data [System.ComponentModel.BrowsableAttribute(false)] public int Count { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] - public System.Data.DataViewManager DataViewManager { get { throw null; } } + public System.Data.DataViewManager? DataViewManager { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsInitialized { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] protected bool IsOpen { get { throw null; } } public System.Data.DataRowView this[int recordIndex] { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] - public virtual string RowFilter { get { throw null; } set { } } + public virtual string? RowFilter { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.DataViewRowState.CurrentRows)] public System.Data.DataViewRowState RowStateFilter { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] - public string Sort { get { throw null; } set { } } + public string? Sort { get { throw null; } set { } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } - object System.Collections.IList.this[int recordIndex] { get { throw null; } set { } } + object? System.Collections.IList.this[int recordIndex] { get { throw null; } set { } } +#nullable disable bool System.ComponentModel.IBindingList.AllowEdit { get { throw null; } } bool System.ComponentModel.IBindingList.AllowNew { get { throw null; } } bool System.ComponentModel.IBindingList.AllowRemove { get { throw null; } } @@ -880,8 +918,9 @@ namespace System.Data System.ComponentModel.ListSortDescriptionCollection System.ComponentModel.IBindingListView.SortDescriptions { get { throw null; } } bool System.ComponentModel.IBindingListView.SupportsAdvancedSorting { get { throw null; } } bool System.ComponentModel.IBindingListView.SupportsFiltering { get { throw null; } } - public event System.EventHandler Initialized { add { } remove { } } - public event System.ComponentModel.ListChangedEventHandler ListChanged { add { } remove { } } +#nullable enable + public event System.EventHandler? Initialized { add { } remove { } } + public event System.ComponentModel.ListChangedEventHandler? ListChanged { add { } remove { } } public virtual System.Data.DataRowView AddNew() { throw null; } public void BeginInit() { } protected void Close() { } @@ -890,23 +929,24 @@ namespace System.Data public void Delete(int index) { } protected override void Dispose(bool disposing) { } public void EndInit() { } - public virtual bool Equals(System.Data.DataView view) { throw null; } - public int Find(object key) { throw null; } - public int Find(object[] key) { throw null; } - public System.Data.DataRowView[] FindRows(object key) { throw null; } - public System.Data.DataRowView[] FindRows(object[] key) { throw null; } + public virtual bool Equals(System.Data.DataView? view) { throw null; } + public int Find(object? key) { throw null; } + public int Find(object?[] key) { throw null; } + public System.Data.DataRowView[] FindRows(object? key) { throw null; } + public System.Data.DataRowView[] FindRows(object?[] key) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } protected virtual void IndexListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) { } protected virtual void OnListChanged(System.ComponentModel.ListChangedEventArgs e) { } protected void Open() { } protected void Reset() { } - int System.Collections.IList.Add(object value) { throw null; } + int System.Collections.IList.Add(object? value) { throw null; } void System.Collections.IList.Clear() { } - bool System.Collections.IList.Contains(object value) { throw null; } - int System.Collections.IList.IndexOf(object value) { throw null; } - void System.Collections.IList.Insert(int index, object value) { } - void System.Collections.IList.Remove(object value) { } + bool System.Collections.IList.Contains(object? value) { throw null; } + int System.Collections.IList.IndexOf(object? value) { throw null; } + void System.Collections.IList.Insert(int index, object? value) { } + void System.Collections.IList.Remove(object? value) { } void System.Collections.IList.RemoveAt(int index) { } +#nullable disable void System.ComponentModel.IBindingList.AddIndex(System.ComponentModel.PropertyDescriptor property) { } object System.ComponentModel.IBindingList.AddNew() { throw null; } void System.ComponentModel.IBindingList.ApplySort(System.ComponentModel.PropertyDescriptor property, System.ComponentModel.ListSortDirection direction) { } @@ -917,19 +957,21 @@ namespace System.Data void System.ComponentModel.IBindingListView.RemoveFilter() { } System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(System.ComponentModel.PropertyDescriptor[] listAccessors) { throw null; } string System.ComponentModel.ITypedList.GetListName(System.ComponentModel.PropertyDescriptor[] listAccessors) { throw null; } +#nullable enable public System.Data.DataTable ToTable() { throw null; } public System.Data.DataTable ToTable(bool distinct, params string[] columnNames) { throw null; } - public System.Data.DataTable ToTable(string tableName) { throw null; } - public System.Data.DataTable ToTable(string tableName, bool distinct, params string[] columnNames) { throw null; } + public System.Data.DataTable ToTable(string? tableName) { throw null; } + public System.Data.DataTable ToTable(string? tableName, bool distinct, params string[] columnNames) { throw null; } protected void UpdateIndex() { } protected virtual void UpdateIndex(bool force) { } } public partial class DataViewManager : System.ComponentModel.MarshalByValueComponent, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList, System.ComponentModel.IBindingList, System.ComponentModel.ITypedList { public DataViewManager() { } - public DataViewManager(System.Data.DataSet dataSet) { } + public DataViewManager(System.Data.DataSet? dataSet) { } [System.ComponentModel.DefaultValueAttribute(null)] - public System.Data.DataSet DataSet { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNull] + public System.Data.DataSet? DataSet { get { throw null; } set { } } public string DataViewSettingCollectionString { get { throw null; } set { } } [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Data.DataViewSettingCollection DataViewSettings { get { throw null; } } @@ -938,7 +980,8 @@ namespace System.Data object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } - object System.Collections.IList.this[int index] { get { throw null; } set { } } + object? System.Collections.IList.this[int index] { get { throw null; } set { } } +#nullable disable bool System.ComponentModel.IBindingList.AllowEdit { get { throw null; } } bool System.ComponentModel.IBindingList.AllowNew { get { throw null; } } bool System.ComponentModel.IBindingList.AllowRemove { get { throw null; } } @@ -948,19 +991,21 @@ namespace System.Data bool System.ComponentModel.IBindingList.SupportsChangeNotification { get { throw null; } } bool System.ComponentModel.IBindingList.SupportsSearching { get { throw null; } } bool System.ComponentModel.IBindingList.SupportsSorting { get { throw null; } } - public event System.ComponentModel.ListChangedEventHandler ListChanged { add { } remove { } } +#nullable enable + public event System.ComponentModel.ListChangedEventHandler? ListChanged { add { } remove { } } public System.Data.DataView CreateDataView(System.Data.DataTable table) { throw null; } protected virtual void OnListChanged(System.ComponentModel.ListChangedEventArgs e) { } protected virtual void RelationCollectionChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } - int System.Collections.IList.Add(object value) { throw null; } + int System.Collections.IList.Add(object? value) { throw null; } void System.Collections.IList.Clear() { } - bool System.Collections.IList.Contains(object value) { throw null; } - int System.Collections.IList.IndexOf(object value) { throw null; } - void System.Collections.IList.Insert(int index, object value) { } - void System.Collections.IList.Remove(object value) { } + bool System.Collections.IList.Contains(object? value) { throw null; } + int System.Collections.IList.IndexOf(object? value) { throw null; } + void System.Collections.IList.Insert(int index, object? value) { } + void System.Collections.IList.Remove(object? value) { } void System.Collections.IList.RemoveAt(int index) { } +#nullable disable void System.ComponentModel.IBindingList.AddIndex(System.ComponentModel.PropertyDescriptor property) { } object System.ComponentModel.IBindingList.AddNew() { throw null; } void System.ComponentModel.IBindingList.ApplySort(System.ComponentModel.PropertyDescriptor property, System.ComponentModel.ListSortDirection direction) { } @@ -969,6 +1014,7 @@ namespace System.Data void System.ComponentModel.IBindingList.RemoveSort() { } System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(System.ComponentModel.PropertyDescriptor[] listAccessors) { throw null; } string System.ComponentModel.ITypedList.GetListName(System.ComponentModel.PropertyDescriptor[] listAccessors) { throw null; } +#nullable enable protected virtual void TableCollectionChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e) { } } [System.FlagsAttribute] @@ -989,12 +1035,14 @@ namespace System.Data internal DataViewSetting() { } public bool ApplyDefaultSort { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - public System.Data.DataViewManager DataViewManager { get { throw null; } } + public System.Data.DataViewManager? DataViewManager { get { throw null; } } + [System.Diagnostics.CodeAnalysis.AllowNull] public string RowFilter { get { throw null; } set { } } public System.Data.DataViewRowState RowStateFilter { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNull] public string Sort { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] - public System.Data.DataTable Table { get { throw null; } } + public System.Data.DataTable? Table { get { throw null; } } } public partial class DataViewSettingCollection : System.Collections.ICollection, System.Collections.IEnumerable { @@ -1006,8 +1054,9 @@ namespace System.Data [System.ComponentModel.BrowsableAttribute(false)] public bool IsSynchronized { get { throw null; } } public virtual System.Data.DataViewSetting this[System.Data.DataTable table] { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.MaybeNull] public virtual System.Data.DataViewSetting this[int index] { get { throw null; } set { } } - public virtual System.Data.DataViewSetting this[string tableName] { get { throw null; } } + public virtual System.Data.DataViewSetting? this[string tableName] { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public object SyncRoot { get { throw null; } } public void CopyTo(System.Array ar, int index) { } @@ -1017,10 +1066,11 @@ namespace System.Data public sealed partial class DBConcurrencyException : System.SystemException { public DBConcurrencyException() { } - public DBConcurrencyException(string message) { } - public DBConcurrencyException(string message, System.Exception inner) { } - public DBConcurrencyException(string message, System.Exception inner, System.Data.DataRow[] dataRows) { } - public System.Data.DataRow Row { get { throw null; } set { } } + public DBConcurrencyException(string? message) { } + public DBConcurrencyException(string? message, System.Exception? inner) { } + public DBConcurrencyException(string? message, System.Exception? inner, System.Data.DataRow[]? dataRows) { } + [System.Diagnostics.CodeAnalysis.DisallowNull] + public System.Data.DataRow? Row { get { throw null; } set { } } public int RowCount { get { throw null; } } public void CopyToRows(System.Data.DataRow[] array) { } public void CopyToRows(System.Data.DataRow[] array, int arrayIndex) { } @@ -1060,15 +1110,15 @@ namespace System.Data { public DeletedRowInaccessibleException() { } protected DeletedRowInaccessibleException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public DeletedRowInaccessibleException(string s) { } - public DeletedRowInaccessibleException(string message, System.Exception innerException) { } + public DeletedRowInaccessibleException(string? s) { } + public DeletedRowInaccessibleException(string? message, System.Exception? innerException) { } } public partial class DuplicateNameException : System.Data.DataException { public DuplicateNameException() { } protected DuplicateNameException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public DuplicateNameException(string s) { } - public DuplicateNameException(string message, System.Exception innerException) { } + public DuplicateNameException(string? s) { } + public DuplicateNameException(string? message, System.Exception? innerException) { } } public abstract partial class EnumerableRowCollection : System.Collections.IEnumerable { @@ -1099,16 +1149,16 @@ namespace System.Data { public EvaluateException() { } protected EvaluateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public EvaluateException(string s) { } - public EvaluateException(string message, System.Exception innerException) { } + public EvaluateException(string? s) { } + public EvaluateException(string? message, System.Exception? innerException) { } } public partial class FillErrorEventArgs : System.EventArgs { - public FillErrorEventArgs(System.Data.DataTable dataTable, object[] values) { } + public FillErrorEventArgs(System.Data.DataTable? dataTable, object?[]? values) { } public bool Continue { get { throw null; } set { } } - public System.Data.DataTable DataTable { get { throw null; } } - public System.Exception Errors { get { throw null; } set { } } - public object[] Values { get { throw null; } } + public System.Data.DataTable? DataTable { get { throw null; } } + public System.Exception? Errors { get { throw null; } set { } } + public object?[] Values { get { throw null; } } } public delegate void FillErrorEventHandler(object sender, System.Data.FillErrorEventArgs e); [System.ComponentModel.DefaultPropertyAttribute("ConstraintName")] @@ -1116,12 +1166,12 @@ namespace System.Data { public ForeignKeyConstraint(System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { } public ForeignKeyConstraint(System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { } - public ForeignKeyConstraint(string constraintName, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { } - public ForeignKeyConstraint(string constraintName, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { } + public ForeignKeyConstraint(string? constraintName, System.Data.DataColumn parentColumn, System.Data.DataColumn childColumn) { } + public ForeignKeyConstraint(string? constraintName, System.Data.DataColumn[] parentColumns, System.Data.DataColumn[] childColumns) { } [System.ComponentModel.BrowsableAttribute(false)] - public ForeignKeyConstraint(string constraintName, string parentTableName, string parentTableNamespace, string[] parentColumnNames, string[] childColumnNames, System.Data.AcceptRejectRule acceptRejectRule, System.Data.Rule deleteRule, System.Data.Rule updateRule) { } + public ForeignKeyConstraint(string? constraintName, string? parentTableName, string? parentTableNamespace, string[] parentColumnNames, string[] childColumnNames, System.Data.AcceptRejectRule acceptRejectRule, System.Data.Rule deleteRule, System.Data.Rule updateRule) { } [System.ComponentModel.BrowsableAttribute(false)] - public ForeignKeyConstraint(string constraintName, string parentTableName, string[] parentColumnNames, string[] childColumnNames, System.Data.AcceptRejectRule acceptRejectRule, System.Data.Rule deleteRule, System.Data.Rule updateRule) { } + public ForeignKeyConstraint(string? constraintName, string? parentTableName, string[] parentColumnNames, string[] childColumnNames, System.Data.AcceptRejectRule acceptRejectRule, System.Data.Rule deleteRule, System.Data.Rule updateRule) { } [System.ComponentModel.DefaultValueAttribute(System.Data.AcceptRejectRule.None)] public virtual System.Data.AcceptRejectRule AcceptRejectRule { get { throw null; } set { } } [System.ComponentModel.ReadOnlyAttribute(true)] @@ -1133,10 +1183,10 @@ namespace System.Data [System.ComponentModel.ReadOnlyAttribute(true)] public virtual System.Data.DataTable RelatedTable { get { throw null; } } [System.ComponentModel.ReadOnlyAttribute(true)] - public override System.Data.DataTable Table { get { throw null; } } + public override System.Data.DataTable? Table { get { throw null; } } [System.ComponentModel.DefaultValueAttribute(System.Data.Rule.Cascade)] public virtual System.Data.Rule UpdateRule { get { throw null; } set { } } - public override bool Equals(object key) { throw null; } + public override bool Equals(object? key) { throw null; } public override int GetHashCode() { throw null; } } public partial interface IColumnMapping @@ -1148,9 +1198,9 @@ namespace System.Data { object this[string index] { get; set; } System.Data.IColumnMapping Add(string sourceColumnName, string dataSetColumnName); - bool Contains(string sourceColumnName); + bool Contains(string? sourceColumnName); System.Data.IColumnMapping GetByDataSetColumn(string dataSetColumnName); - int IndexOf(string sourceColumnName); + int IndexOf(string? sourceColumnName); void RemoveAt(string sourceColumnName); } public partial interface IDataAdapter @@ -1163,7 +1213,6 @@ namespace System.Data System.Data.IDataParameter[] GetFillParameters(); int Update(System.Data.DataSet dataSet); } -#nullable enable public partial interface IDataParameter { System.Data.DbType DbType { get; set; } @@ -1253,15 +1302,13 @@ namespace System.Data System.Data.IDbCommand CreateCommand(); void Open(); } -#nullable disable public partial interface IDbDataAdapter : System.Data.IDataAdapter { - System.Data.IDbCommand DeleteCommand { get; set; } - System.Data.IDbCommand InsertCommand { get; set; } - System.Data.IDbCommand SelectCommand { get; set; } - System.Data.IDbCommand UpdateCommand { get; set; } + System.Data.IDbCommand? DeleteCommand { get; set; } + System.Data.IDbCommand? InsertCommand { get; set; } + System.Data.IDbCommand? SelectCommand { get; set; } + System.Data.IDbCommand? UpdateCommand { get; set; } } -#nullable enable public partial interface IDbDataParameter : System.Data.IDataParameter { byte Precision { get; set; } @@ -1275,13 +1322,12 @@ namespace System.Data void Commit(); void Rollback(); } -#nullable disable public partial class InRowChangingEventException : System.Data.DataException { public InRowChangingEventException() { } protected InRowChangingEventException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public InRowChangingEventException(string s) { } - public InRowChangingEventException(string message, System.Exception innerException) { } + public InRowChangingEventException(string? s) { } + public InRowChangingEventException(string? message, System.Exception? innerException) { } } public partial class InternalDataCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable { @@ -1302,15 +1348,15 @@ namespace System.Data { public InvalidConstraintException() { } protected InvalidConstraintException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public InvalidConstraintException(string s) { } - public InvalidConstraintException(string message, System.Exception innerException) { } + public InvalidConstraintException(string? s) { } + public InvalidConstraintException(string? message, System.Exception? innerException) { } } public partial class InvalidExpressionException : System.Data.DataException { public InvalidExpressionException() { } protected InvalidExpressionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public InvalidExpressionException(string s) { } - public InvalidExpressionException(string message, System.Exception innerException) { } + public InvalidExpressionException(string? s) { } + public InvalidExpressionException(string? message, System.Exception? innerException) { } } public enum IsolationLevel { @@ -1332,9 +1378,9 @@ namespace System.Data { object this[string index] { get; set; } System.Data.ITableMapping Add(string sourceTableName, string dataSetTableName); - bool Contains(string sourceTableName); + bool Contains(string? sourceTableName); System.Data.ITableMapping GetByDataSetTable(string dataSetTableName); - int IndexOf(string sourceTableName); + int IndexOf(string? sourceTableName); void RemoveAt(string sourceTableName); } public enum KeyRestrictionBehavior @@ -1357,9 +1403,9 @@ namespace System.Data } public partial class MergeFailedEventArgs : System.EventArgs { - public MergeFailedEventArgs(System.Data.DataTable table, string conflict) { } + public MergeFailedEventArgs(System.Data.DataTable? table, string conflict) { } public string Conflict { get { throw null; } } - public System.Data.DataTable Table { get { throw null; } } + public System.Data.DataTable? Table { get { throw null; } } } public delegate void MergeFailedEventHandler(object sender, System.Data.MergeFailedEventArgs e); public enum MissingMappingAction @@ -1372,8 +1418,8 @@ namespace System.Data { public MissingPrimaryKeyException() { } protected MissingPrimaryKeyException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public MissingPrimaryKeyException(string s) { } - public MissingPrimaryKeyException(string message, System.Exception innerException) { } + public MissingPrimaryKeyException(string? s) { } + public MissingPrimaryKeyException(string? message, System.Exception? innerException) { } } public enum MissingSchemaAction { @@ -1386,8 +1432,8 @@ namespace System.Data { public NoNullAllowedException() { } protected NoNullAllowedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public NoNullAllowedException(string s) { } - public NoNullAllowedException(string message, System.Exception innerException) { } + public NoNullAllowedException(string? s) { } + public NoNullAllowedException(string? message, System.Exception? innerException) { } } public sealed partial class OrderedEnumerableRowCollection : System.Data.EnumerableRowCollection { @@ -1410,15 +1456,15 @@ namespace System.Data { public ReadOnlyException() { } protected ReadOnlyException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public ReadOnlyException(string s) { } - public ReadOnlyException(string message, System.Exception innerException) { } + public ReadOnlyException(string? s) { } + public ReadOnlyException(string? message, System.Exception? innerException) { } } public partial class RowNotInTableException : System.Data.DataException { public RowNotInTableException() { } protected RowNotInTableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public RowNotInTableException(string s) { } - public RowNotInTableException(string message, System.Exception innerException) { } + public RowNotInTableException(string? s) { } + public RowNotInTableException(string? message, System.Exception? innerException) { } } public enum Rule { @@ -1476,7 +1522,6 @@ namespace System.Data DateTime2 = 33, DateTimeOffset = 34, } -#nullable enable public sealed partial class StateChangeEventArgs : System.EventArgs { public StateChangeEventArgs(System.Data.ConnectionState originalState, System.Data.ConnectionState currentState) { } @@ -1484,7 +1529,6 @@ namespace System.Data public System.Data.ConnectionState OriginalState { get { throw null; } } } public delegate void StateChangeEventHandler(object sender, System.Data.StateChangeEventArgs e); -#nullable disable public sealed partial class StatementCompletedEventArgs : System.EventArgs { public StatementCompletedEventArgs(int recordCount) { } @@ -1503,19 +1547,20 @@ namespace System.Data { public StrongTypingException() { } protected StrongTypingException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public StrongTypingException(string message) { } - public StrongTypingException(string s, System.Exception innerException) { } + public StrongTypingException(string? message) { } + public StrongTypingException(string? s, System.Exception? innerException) { } } public partial class SyntaxErrorException : System.Data.InvalidExpressionException { public SyntaxErrorException() { } protected SyntaxErrorException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public SyntaxErrorException(string s) { } - public SyntaxErrorException(string message, System.Exception innerException) { } + public SyntaxErrorException(string? s) { } + public SyntaxErrorException(string? message, System.Exception? innerException) { } } public static partial class TypedTableBaseExtensions { public static System.Data.EnumerableRowCollection AsEnumerable(this System.Data.TypedTableBase source) where TRow : System.Data.DataRow { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNull] public static TRow ElementAtOrDefault(this System.Data.TypedTableBase source, int index) where TRow : System.Data.DataRow { throw null; } public static System.Data.OrderedEnumerableRowCollection OrderByDescending(this System.Data.TypedTableBase source, System.Func keySelector) where TRow : System.Data.DataRow { throw null; } public static System.Data.OrderedEnumerableRowCollection OrderByDescending(this System.Data.TypedTableBase source, System.Func keySelector, System.Collections.Generic.IComparer comparer) where TRow : System.Data.DataRow { throw null; } @@ -1539,18 +1584,18 @@ namespace System.Data public UniqueConstraint(System.Data.DataColumn column, bool isPrimaryKey) { } public UniqueConstraint(System.Data.DataColumn[] columns) { } public UniqueConstraint(System.Data.DataColumn[] columns, bool isPrimaryKey) { } - public UniqueConstraint(string name, System.Data.DataColumn column) { } - public UniqueConstraint(string name, System.Data.DataColumn column, bool isPrimaryKey) { } - public UniqueConstraint(string name, System.Data.DataColumn[] columns) { } - public UniqueConstraint(string name, System.Data.DataColumn[] columns, bool isPrimaryKey) { } + public UniqueConstraint(string? name, System.Data.DataColumn column) { } + public UniqueConstraint(string? name, System.Data.DataColumn column, bool isPrimaryKey) { } + public UniqueConstraint(string? name, System.Data.DataColumn[] columns) { } + public UniqueConstraint(string? name, System.Data.DataColumn[] columns, bool isPrimaryKey) { } [System.ComponentModel.BrowsableAttribute(false)] - public UniqueConstraint(string name, string[] columnNames, bool isPrimaryKey) { } + public UniqueConstraint(string name, string[]? columnNames, bool isPrimaryKey) { } [System.ComponentModel.ReadOnlyAttribute(true)] public virtual System.Data.DataColumn[] Columns { get { throw null; } } public bool IsPrimaryKey { get { throw null; } } [System.ComponentModel.ReadOnlyAttribute(true)] - public override System.Data.DataTable Table { get { throw null; } } - public override bool Equals(object key2) { throw null; } + public override System.Data.DataTable? Table { get { throw null; } } + public override bool Equals(object? key2) { throw null; } public override int GetHashCode() { throw null; } } public enum UpdateRowSource @@ -1571,8 +1616,8 @@ namespace System.Data { public VersionNotFoundException() { } protected VersionNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public VersionNotFoundException(string s) { } - public VersionNotFoundException(string message, System.Exception innerException) { } + public VersionNotFoundException(string? s) { } + public VersionNotFoundException(string? message, System.Exception? innerException) { } } public enum XmlReadMode { @@ -1619,7 +1664,7 @@ namespace System.Data.Common System.Data.ITableMappingCollection System.Data.IDataAdapter.TableMappings { get { throw null; } } [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Data.Common.DataTableMappingCollection TableMappings { get { throw null; } } - public event System.Data.FillErrorEventHandler FillError { add { } remove { } } + public event System.Data.FillErrorEventHandler? FillError { add { } remove { } } [System.ObsoleteAttribute("CloneInternals() has been deprecated. Use the DataAdapter(DataAdapter from) constructor. https://go.microsoft.com/fwlink/?linkid=14202")] protected virtual System.Data.Common.DataAdapter CloneInternals() { throw null; } protected virtual System.Data.Common.DataTableMappingCollection CreateTableMappings() { throw null; } @@ -1630,7 +1675,7 @@ namespace System.Data.Common protected virtual int Fill(System.Data.DataTable[] dataTables, System.Data.IDataReader dataReader, int startRecord, int maxRecords) { throw null; } public virtual System.Data.DataTable[] FillSchema(System.Data.DataSet dataSet, System.Data.SchemaType schemaType) { throw null; } protected virtual System.Data.DataTable[] FillSchema(System.Data.DataSet dataSet, System.Data.SchemaType schemaType, string srcTable, System.Data.IDataReader dataReader) { throw null; } - protected virtual System.Data.DataTable FillSchema(System.Data.DataTable dataTable, System.Data.SchemaType schemaType, System.Data.IDataReader dataReader) { throw null; } + protected virtual System.Data.DataTable? FillSchema(System.Data.DataTable dataTable, System.Data.SchemaType schemaType, System.Data.IDataReader dataReader) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public virtual System.Data.IDataParameter[] GetFillParameters() { throw null; } protected bool HasTableMappings() { throw null; } @@ -1647,15 +1692,17 @@ namespace System.Data.Common public sealed partial class DataColumnMapping : System.MarshalByRefObject, System.Data.IColumnMapping, System.ICloneable { public DataColumnMapping() { } - public DataColumnMapping(string sourceColumn, string dataSetColumn) { } + public DataColumnMapping(string? sourceColumn, string? dataSetColumn) { } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string DataSetColumn { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string SourceColumn { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public System.Data.DataColumn GetDataColumnBySchemaAction(System.Data.DataTable dataTable, System.Type dataType, System.Data.MissingSchemaAction schemaAction) { throw null; } + public System.Data.DataColumn? GetDataColumnBySchemaAction(System.Data.DataTable dataTable, System.Type? dataType, System.Data.MissingSchemaAction schemaAction) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Data.DataColumn GetDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, System.Data.DataTable dataTable, System.Type dataType, System.Data.MissingSchemaAction schemaAction) { throw null; } + public static System.Data.DataColumn GetDataColumnBySchemaAction(string? sourceColumn, string? dataSetColumn, System.Data.DataTable dataTable, System.Type? dataType, System.Data.MissingSchemaAction schemaAction) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } } @@ -1675,53 +1722,55 @@ namespace System.Data.Common object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } - object System.Collections.IList.this[int index] { get { throw null; } set { } } + object? System.Collections.IList.this[int index] { get { throw null; } set { } } object System.Data.IColumnMappingCollection.this[string index] { get { throw null; } set { } } - public int Add(object value) { throw null; } - public System.Data.Common.DataColumnMapping Add(string sourceColumn, string dataSetColumn) { throw null; } + public int Add(object? value) { throw null; } + public System.Data.Common.DataColumnMapping Add(string? sourceColumn, string? dataSetColumn) { throw null; } public void AddRange(System.Array values) { } public void AddRange(System.Data.Common.DataColumnMapping[] values) { } public void Clear() { } - public bool Contains(object value) { throw null; } - public bool Contains(string value) { throw null; } + public bool Contains(object? value) { throw null; } + public bool Contains(string? value) { throw null; } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Data.Common.DataColumnMapping[] array, int index) { } public System.Data.Common.DataColumnMapping GetByDataSetColumn(string value) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Data.Common.DataColumnMapping GetColumnMappingBySchemaAction(System.Data.Common.DataColumnMappingCollection columnMappings, string sourceColumn, System.Data.MissingMappingAction mappingAction) { throw null; } + public static System.Data.Common.DataColumnMapping? GetColumnMappingBySchemaAction(System.Data.Common.DataColumnMappingCollection? columnMappings, string sourceColumn, System.Data.MissingMappingAction mappingAction) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Data.DataColumn GetDataColumn(System.Data.Common.DataColumnMappingCollection columnMappings, string sourceColumn, System.Type dataType, System.Data.DataTable dataTable, System.Data.MissingMappingAction mappingAction, System.Data.MissingSchemaAction schemaAction) { throw null; } + public static System.Data.DataColumn? GetDataColumn(System.Data.Common.DataColumnMappingCollection? columnMappings, string sourceColumn, System.Type? dataType, System.Data.DataTable dataTable, System.Data.MissingMappingAction mappingAction, System.Data.MissingSchemaAction schemaAction) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } - public int IndexOf(object value) { throw null; } - public int IndexOf(string sourceColumn) { throw null; } - public int IndexOfDataSetColumn(string dataSetColumn) { throw null; } + public int IndexOf(object? value) { throw null; } + public int IndexOf(string? sourceColumn) { throw null; } + public int IndexOfDataSetColumn(string? dataSetColumn) { throw null; } public void Insert(int index, System.Data.Common.DataColumnMapping value) { } - public void Insert(int index, object value) { } + public void Insert(int index, object? value) { } public void Remove(System.Data.Common.DataColumnMapping value) { } - public void Remove(object value) { } + public void Remove(object? value) { } public void RemoveAt(int index) { } public void RemoveAt(string sourceColumn) { } - System.Data.IColumnMapping System.Data.IColumnMappingCollection.Add(string sourceColumnName, string dataSetColumnName) { throw null; } + System.Data.IColumnMapping System.Data.IColumnMappingCollection.Add(string? sourceColumnName, string? dataSetColumnName) { throw null; } System.Data.IColumnMapping System.Data.IColumnMappingCollection.GetByDataSetColumn(string dataSetColumnName) { throw null; } } public sealed partial class DataTableMapping : System.MarshalByRefObject, System.Data.ITableMapping, System.ICloneable { public DataTableMapping() { } - public DataTableMapping(string sourceTable, string dataSetTable) { } - public DataTableMapping(string sourceTable, string dataSetTable, System.Data.Common.DataColumnMapping[] columnMappings) { } + public DataTableMapping(string? sourceTable, string? dataSetTable) { } + public DataTableMapping(string? sourceTable, string? dataSetTable, System.Data.Common.DataColumnMapping[]? columnMappings) { } [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)] public System.Data.Common.DataColumnMappingCollection ColumnMappings { get { throw null; } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string DataSetTable { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public string SourceTable { get { throw null; } set { } } System.Data.IColumnMappingCollection System.Data.ITableMapping.ColumnMappings { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public System.Data.Common.DataColumnMapping GetColumnMappingBySchemaAction(string sourceColumn, System.Data.MissingMappingAction mappingAction) { throw null; } + public System.Data.Common.DataColumnMapping? GetColumnMappingBySchemaAction(string sourceColumn, System.Data.MissingMappingAction mappingAction) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public System.Data.DataColumn GetDataColumn(string sourceColumn, System.Type dataType, System.Data.DataTable dataTable, System.Data.MissingMappingAction mappingAction, System.Data.MissingSchemaAction schemaAction) { throw null; } + public System.Data.DataColumn? GetDataColumn(string sourceColumn, System.Type? dataType, System.Data.DataTable dataTable, System.Data.MissingMappingAction mappingAction, System.Data.MissingSchemaAction schemaAction) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public System.Data.DataTable GetDataTableBySchemaAction(System.Data.DataSet dataSet, System.Data.MissingSchemaAction schemaAction) { throw null; } + public System.Data.DataTable? GetDataTableBySchemaAction(System.Data.DataSet dataSet, System.Data.MissingSchemaAction schemaAction) { throw null; } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } } @@ -1742,34 +1791,33 @@ namespace System.Data.Common object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } - object System.Collections.IList.this[int index] { get { throw null; } set { } } + object? System.Collections.IList.this[int index] { get { throw null; } set { } } object System.Data.ITableMappingCollection.this[string index] { get { throw null; } set { } } - public int Add(object value) { throw null; } - public System.Data.Common.DataTableMapping Add(string sourceTable, string dataSetTable) { throw null; } + public int Add(object? value) { throw null; } + public System.Data.Common.DataTableMapping Add(string? sourceTable, string? dataSetTable) { throw null; } public void AddRange(System.Array values) { } public void AddRange(System.Data.Common.DataTableMapping[] values) { } public void Clear() { } - public bool Contains(object value) { throw null; } - public bool Contains(string value) { throw null; } + public bool Contains(object? value) { throw null; } + public bool Contains(string? value) { throw null; } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Data.Common.DataTableMapping[] array, int index) { } public System.Data.Common.DataTableMapping GetByDataSetTable(string dataSetTable) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Data.Common.DataTableMapping GetTableMappingBySchemaAction(System.Data.Common.DataTableMappingCollection tableMappings, string sourceTable, string dataSetTable, System.Data.MissingMappingAction mappingAction) { throw null; } - public int IndexOf(object value) { throw null; } - public int IndexOf(string sourceTable) { throw null; } - public int IndexOfDataSetTable(string dataSetTable) { throw null; } + public static System.Data.Common.DataTableMapping? GetTableMappingBySchemaAction(System.Data.Common.DataTableMappingCollection? tableMappings, string sourceTable, string dataSetTable, System.Data.MissingMappingAction mappingAction) { throw null; } + public int IndexOf(object? value) { throw null; } + public int IndexOf(string? sourceTable) { throw null; } + public int IndexOfDataSetTable(string? dataSetTable) { throw null; } public void Insert(int index, System.Data.Common.DataTableMapping value) { } - public void Insert(int index, object value) { } + public void Insert(int index, object? value) { } public void Remove(System.Data.Common.DataTableMapping value) { } - public void Remove(object value) { } + public void Remove(object? value) { } public void RemoveAt(int index) { } public void RemoveAt(string sourceTable) { } System.Data.ITableMapping System.Data.ITableMappingCollection.Add(string sourceTableName, string dataSetTableName) { throw null; } System.Data.ITableMapping System.Data.ITableMappingCollection.GetByDataSetTable(string dataSetTableName) { throw null; } } -#nullable enable public abstract partial class DbColumn { protected DbColumn() { } @@ -1857,24 +1905,27 @@ namespace System.Data.Common System.Data.IDataReader System.Data.IDbCommand.ExecuteReader() { throw null; } System.Data.IDataReader System.Data.IDbCommand.ExecuteReader(System.Data.CommandBehavior behavior) { throw null; } } -#nullable disable public abstract partial class DbCommandBuilder : System.ComponentModel.Component { protected DbCommandBuilder() { } [System.ComponentModel.DefaultValueAttribute(System.Data.Common.CatalogLocation.Start)] public virtual System.Data.Common.CatalogLocation CatalogLocation { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(".")] + [System.Diagnostics.CodeAnalysis.AllowNull] public virtual string CatalogSeparator { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(System.Data.ConflictOption.CompareAllSearchableValues)] public virtual System.Data.ConflictOption ConflictOption { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.Common.DbDataAdapter DataAdapter { get { throw null; } set { } } + public System.Data.Common.DbDataAdapter? DataAdapter { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public virtual string QuotePrefix { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute("")] + [System.Diagnostics.CodeAnalysis.AllowNull] public virtual string QuoteSuffix { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(".")] + [System.Diagnostics.CodeAnalysis.AllowNull] public virtual string SchemaSeparator { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(false)] public bool SetAllValues { get { throw null; } set { } } @@ -1890,14 +1941,13 @@ namespace System.Data.Common protected virtual System.Data.DataTable GetSchemaTable(System.Data.Common.DbCommand sourceCommand) { throw null; } public System.Data.Common.DbCommand GetUpdateCommand() { throw null; } public System.Data.Common.DbCommand GetUpdateCommand(bool useColumnsForParameterNames) { throw null; } - protected virtual System.Data.Common.DbCommand InitializeCommand(System.Data.Common.DbCommand command) { throw null; } + protected virtual System.Data.Common.DbCommand InitializeCommand(System.Data.Common.DbCommand? command) { throw null; } public virtual string QuoteIdentifier(string unquotedIdentifier) { throw null; } public virtual void RefreshSchema() { } protected void RowUpdatingHandler(System.Data.Common.RowUpdatingEventArgs rowUpdatingEvent) { } protected abstract void SetRowUpdatingHandler(System.Data.Common.DbDataAdapter adapter); public virtual string UnquoteIdentifier(string quotedIdentifier) { throw null; } } -#nullable enable public abstract partial class DbConnection : System.ComponentModel.Component, System.Data.IDbConnection, System.IDisposable, System.IAsyncDisposable { protected DbConnection() { } @@ -1988,7 +2038,6 @@ namespace System.Data.Common System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object keyword) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } -#nullable disable System.ComponentModel.AttributeCollection System.ComponentModel.ICustomTypeDescriptor.GetAttributes() { throw null; } string System.ComponentModel.ICustomTypeDescriptor.GetClassName() { throw null; } string System.ComponentModel.ICustomTypeDescriptor.GetComponentName() { throw null; } @@ -2001,11 +2050,9 @@ namespace System.Data.Common System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { throw null; } System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties(System.Attribute[] attributes) { throw null; } object System.ComponentModel.ICustomTypeDescriptor.GetPropertyOwner(System.ComponentModel.PropertyDescriptor pd) { throw null; } -#nullable enable public override string ToString() { throw null; } public virtual bool TryGetValue(string keyword, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out object? value) { throw null; } } -#nullable disable public abstract partial class DbDataAdapter : System.Data.Common.DataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable { public const string DefaultSourceTableName = "Table"; @@ -2013,23 +2060,23 @@ namespace System.Data.Common protected DbDataAdapter(System.Data.Common.DbDataAdapter adapter) { } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.Common.DbCommand DeleteCommand { get { throw null; } set { } } + public System.Data.Common.DbCommand? DeleteCommand { get { throw null; } set { } } protected internal System.Data.CommandBehavior FillCommandBehavior { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.Common.DbCommand InsertCommand { get { throw null; } set { } } + public System.Data.Common.DbCommand? InsertCommand { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.Common.DbCommand SelectCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } - System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } + public System.Data.Common.DbCommand? SelectCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } + System.Data.IDbCommand? System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(1)] public virtual int UpdateBatchSize { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public System.Data.Common.DbCommand UpdateCommand { get { throw null; } set { } } + public System.Data.Common.DbCommand? UpdateCommand { get { throw null; } set { } } protected virtual int AddToBatch(System.Data.IDbCommand command) { throw null; } protected virtual void ClearBatch() { } protected virtual System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } @@ -2047,10 +2094,10 @@ namespace System.Data.Common public override System.Data.DataTable[] FillSchema(System.Data.DataSet dataSet, System.Data.SchemaType schemaType) { throw null; } protected virtual System.Data.DataTable[] FillSchema(System.Data.DataSet dataSet, System.Data.SchemaType schemaType, System.Data.IDbCommand command, string srcTable, System.Data.CommandBehavior behavior) { throw null; } public System.Data.DataTable[] FillSchema(System.Data.DataSet dataSet, System.Data.SchemaType schemaType, string srcTable) { throw null; } - public System.Data.DataTable FillSchema(System.Data.DataTable dataTable, System.Data.SchemaType schemaType) { throw null; } - protected virtual System.Data.DataTable FillSchema(System.Data.DataTable dataTable, System.Data.SchemaType schemaType, System.Data.IDbCommand command, System.Data.CommandBehavior behavior) { throw null; } + public System.Data.DataTable? FillSchema(System.Data.DataTable dataTable, System.Data.SchemaType schemaType) { throw null; } + protected virtual System.Data.DataTable? FillSchema(System.Data.DataTable dataTable, System.Data.SchemaType schemaType, System.Data.IDbCommand command, System.Data.CommandBehavior behavior) { throw null; } protected virtual System.Data.IDataParameter GetBatchedParameter(int commandIdentifier, int parameterIndex) { throw null; } - protected virtual bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out System.Exception error) { throw null; } + protected virtual bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out System.Exception? error) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public override System.Data.IDataParameter[] GetFillParameters() { throw null; } protected virtual void InitializeBatching() { } @@ -2064,7 +2111,6 @@ namespace System.Data.Common public int Update(System.Data.DataSet dataSet, string srcTable) { throw null; } public int Update(System.Data.DataTable dataTable) { throw null; } } -#nullable enable public abstract partial class DbDataReader : System.MarshalByRefObject, System.Collections.IEnumerable, System.Data.IDataReader, System.Data.IDataRecord, System.IDisposable, System.IAsyncDisposable { protected DbDataReader() { } @@ -2186,7 +2232,6 @@ namespace System.Data.Common protected DbDataSourceEnumerator() { } public abstract System.Data.DataTable GetDataSources(); } -#nullable disable public partial class DbEnumerator : System.Collections.IEnumerator { public DbEnumerator(System.Data.Common.DbDataReader reader) { } @@ -2198,7 +2243,6 @@ namespace System.Data.Common [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Reset() { } } -#nullable enable public abstract partial class DbException : System.Runtime.InteropServices.ExternalException { protected DbException() { } @@ -2416,12 +2460,11 @@ namespace System.Data.Common Insensitive = 1, Sensitive = 2, } -#nullable disable public partial class RowUpdatedEventArgs : System.EventArgs { public RowUpdatedEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { } public System.Data.IDbCommand Command { get { throw null; } } - public System.Exception Errors { get { throw null; } set { } } + public System.Exception? Errors { get { throw null; } set { } } public int RecordsAffected { get { throw null; } } public System.Data.DataRow Row { get { throw null; } } public int RowCount { get { throw null; } } @@ -2434,9 +2477,9 @@ namespace System.Data.Common public partial class RowUpdatingEventArgs : System.EventArgs { public RowUpdatingEventArgs(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { } - protected virtual System.Data.IDbCommand BaseCommand { get { throw null; } set { } } - public System.Data.IDbCommand Command { get { throw null; } set { } } - public System.Exception Errors { get { throw null; } set { } } + protected virtual System.Data.IDbCommand? BaseCommand { get { throw null; } set { } } + public System.Data.IDbCommand? Command { get { throw null; } set { } } + public System.Exception? Errors { get { throw null; } set { } } public System.Data.DataRow Row { get { throw null; } } public System.Data.StatementType StatementType { get { throw null; } } public System.Data.UpdateStatus Status { get { throw null; } set { } } @@ -2507,17 +2550,17 @@ namespace System.Data.SqlTypes private object _dummy; private int _dummyPrimitive; public static readonly System.Data.SqlTypes.SqlBinary Null; - public SqlBinary(byte[] value) { throw null; } + public SqlBinary(byte[]? value) { throw null; } public bool IsNull { get { throw null; } } public byte this[int index] { get { throw null; } } public int Length { get { throw null; } } public byte[] Value { get { throw null; } } public static System.Data.SqlTypes.SqlBinary Add(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlBinary value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlBinary Concat(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } @@ -2527,7 +2570,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlBoolean NotEquals(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public static System.Data.SqlTypes.SqlBinary operator +(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public static System.Data.SqlTypes.SqlBoolean operator ==(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } - public static explicit operator byte[] (System.Data.SqlTypes.SqlBinary x) { throw null; } + public static explicit operator byte[]? (System.Data.SqlTypes.SqlBinary x) { throw null; } public static explicit operator System.Data.SqlTypes.SqlBinary (System.Data.SqlTypes.SqlGuid x) { throw null; } public static System.Data.SqlTypes.SqlBoolean operator >(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public static System.Data.SqlTypes.SqlBoolean operator >=(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } @@ -2535,7 +2578,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlBoolean operator !=(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public static System.Data.SqlTypes.SqlBoolean operator <(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } public static System.Data.SqlTypes.SqlBoolean operator <=(System.Data.SqlTypes.SqlBinary x, System.Data.SqlTypes.SqlBinary y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlGuid ToSqlGuid() { throw null; } @@ -2559,9 +2602,9 @@ namespace System.Data.SqlTypes public bool Value { get { throw null; } } public static System.Data.SqlTypes.SqlBoolean And(System.Data.SqlTypes.SqlBoolean x, System.Data.SqlTypes.SqlBoolean y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlBoolean value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlBoolean x, System.Data.SqlTypes.SqlBoolean y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlBoolean x, System.Data.SqlTypes.SqlBoolean y) { throw null; } @@ -2596,7 +2639,7 @@ namespace System.Data.SqlTypes public static bool operator true(System.Data.SqlTypes.SqlBoolean x) { throw null; } public static System.Data.SqlTypes.SqlBoolean Or(System.Data.SqlTypes.SqlBoolean x, System.Data.SqlTypes.SqlBoolean y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Parse(string s) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlByte ToSqlByte() { throw null; } @@ -2626,10 +2669,10 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlByte BitwiseAnd(System.Data.SqlTypes.SqlByte x, System.Data.SqlTypes.SqlByte y) { throw null; } public static System.Data.SqlTypes.SqlByte BitwiseOr(System.Data.SqlTypes.SqlByte x, System.Data.SqlTypes.SqlByte y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlByte value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlByte Divide(System.Data.SqlTypes.SqlByte x, System.Data.SqlTypes.SqlByte y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlByte x, System.Data.SqlTypes.SqlByte y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlByte x, System.Data.SqlTypes.SqlByte y) { throw null; } @@ -2688,10 +2731,10 @@ namespace System.Data.SqlTypes public sealed partial class SqlBytes : System.Data.SqlTypes.INullable, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable { public SqlBytes() { } - public SqlBytes(byte[] buffer) { } + public SqlBytes(byte[]? buffer) { } public SqlBytes(System.Data.SqlTypes.SqlBinary value) { } - public SqlBytes(System.IO.Stream s) { } - public byte[] Buffer { get { throw null; } } + public SqlBytes(System.IO.Stream? s) { } + public byte[]? Buffer { get { throw null; } } public bool IsNull { get { throw null; } } public byte this[long offset] { get { throw null; } set { } } public long Length { get { throw null; } } @@ -2707,7 +2750,7 @@ namespace System.Data.SqlTypes public void SetLength(long value) { } public void SetNull() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader r) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlBinary ToSqlBinary() { throw null; } @@ -2717,9 +2760,9 @@ namespace System.Data.SqlTypes public sealed partial class SqlChars : System.Data.SqlTypes.INullable, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable { public SqlChars() { } - public SqlChars(char[] buffer) { } + public SqlChars(char[]? buffer) { } public SqlChars(System.Data.SqlTypes.SqlString value) { } - public char[] Buffer { get { throw null; } } + public char[]? Buffer { get { throw null; } } public bool IsNull { get { throw null; } } public char this[long offset] { get { throw null; } set { } } public long Length { get { throw null; } } @@ -2734,7 +2777,7 @@ namespace System.Data.SqlTypes public void SetLength(long value) { } public void SetNull() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader r) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlString ToSqlString() { throw null; } @@ -2773,9 +2816,9 @@ namespace System.Data.SqlTypes public System.DateTime Value { get { throw null; } } public static System.Data.SqlTypes.SqlDateTime Add(System.Data.SqlTypes.SqlDateTime x, System.TimeSpan t) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlDateTime value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlDateTime x, System.Data.SqlTypes.SqlDateTime y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlDateTime x, System.Data.SqlTypes.SqlDateTime y) { throw null; } @@ -2796,7 +2839,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlDateTime operator -(System.Data.SqlTypes.SqlDateTime x, System.TimeSpan t) { throw null; } public static System.Data.SqlTypes.SqlDateTime Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlDateTime Subtract(System.Data.SqlTypes.SqlDateTime x, System.TimeSpan t) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlString ToSqlString() { throw null; } @@ -2829,11 +2872,11 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlDecimal AdjustScale(System.Data.SqlTypes.SqlDecimal n, int digits, bool fRound) { throw null; } public static System.Data.SqlTypes.SqlDecimal Ceiling(System.Data.SqlTypes.SqlDecimal n) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlDecimal value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlDecimal ConvertToPrecScale(System.Data.SqlTypes.SqlDecimal n, int precision, int scale) { throw null; } public static System.Data.SqlTypes.SqlDecimal Divide(System.Data.SqlTypes.SqlDecimal x, System.Data.SqlTypes.SqlDecimal y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlDecimal x, System.Data.SqlTypes.SqlDecimal y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public static System.Data.SqlTypes.SqlDecimal Floor(System.Data.SqlTypes.SqlDecimal n) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } @@ -2872,7 +2915,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlDecimal Round(System.Data.SqlTypes.SqlDecimal n, int position) { throw null; } public static System.Data.SqlTypes.SqlInt32 Sign(System.Data.SqlTypes.SqlDecimal n) { throw null; } public static System.Data.SqlTypes.SqlDecimal Subtract(System.Data.SqlTypes.SqlDecimal x, System.Data.SqlTypes.SqlDecimal y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public double ToDouble() { throw null; } @@ -2901,10 +2944,10 @@ namespace System.Data.SqlTypes public double Value { get { throw null; } } public static System.Data.SqlTypes.SqlDouble Add(System.Data.SqlTypes.SqlDouble x, System.Data.SqlTypes.SqlDouble y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlDouble value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlDouble Divide(System.Data.SqlTypes.SqlDouble x, System.Data.SqlTypes.SqlDouble y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlDouble x, System.Data.SqlTypes.SqlDouble y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlDouble x, System.Data.SqlTypes.SqlDouble y) { throw null; } @@ -2937,7 +2980,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlDouble operator -(System.Data.SqlTypes.SqlDouble x) { throw null; } public static System.Data.SqlTypes.SqlDouble Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlDouble Subtract(System.Data.SqlTypes.SqlDouble x, System.Data.SqlTypes.SqlDouble y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlBoolean ToSqlBoolean() { throw null; } @@ -2964,9 +3007,9 @@ namespace System.Data.SqlTypes public bool IsNull { get { throw null; } } public System.Guid Value { get { throw null; } } public int CompareTo(System.Data.SqlTypes.SqlGuid value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlGuid x, System.Data.SqlTypes.SqlGuid y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlGuid x, System.Data.SqlTypes.SqlGuid y) { throw null; } @@ -2988,7 +3031,7 @@ namespace System.Data.SqlTypes System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } - public byte[] ToByteArray() { throw null; } + public byte[]? ToByteArray() { throw null; } public System.Data.SqlTypes.SqlBinary ToSqlBinary() { throw null; } public System.Data.SqlTypes.SqlString ToSqlString() { throw null; } public override string ToString() { throw null; } @@ -3008,10 +3051,10 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlInt16 BitwiseAnd(System.Data.SqlTypes.SqlInt16 x, System.Data.SqlTypes.SqlInt16 y) { throw null; } public static System.Data.SqlTypes.SqlInt16 BitwiseOr(System.Data.SqlTypes.SqlInt16 x, System.Data.SqlTypes.SqlInt16 y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlInt16 value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlInt16 Divide(System.Data.SqlTypes.SqlInt16 x, System.Data.SqlTypes.SqlInt16 y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlInt16 x, System.Data.SqlTypes.SqlInt16 y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlInt16 x, System.Data.SqlTypes.SqlInt16 y) { throw null; } @@ -3052,7 +3095,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlInt16 operator -(System.Data.SqlTypes.SqlInt16 x) { throw null; } public static System.Data.SqlTypes.SqlInt16 Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlInt16 Subtract(System.Data.SqlTypes.SqlInt16 x, System.Data.SqlTypes.SqlInt16 y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlBoolean ToSqlBoolean() { throw null; } @@ -3082,10 +3125,10 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlInt32 BitwiseAnd(System.Data.SqlTypes.SqlInt32 x, System.Data.SqlTypes.SqlInt32 y) { throw null; } public static System.Data.SqlTypes.SqlInt32 BitwiseOr(System.Data.SqlTypes.SqlInt32 x, System.Data.SqlTypes.SqlInt32 y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlInt32 value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlInt32 Divide(System.Data.SqlTypes.SqlInt32 x, System.Data.SqlTypes.SqlInt32 y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlInt32 x, System.Data.SqlTypes.SqlInt32 y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlInt32 x, System.Data.SqlTypes.SqlInt32 y) { throw null; } @@ -3126,7 +3169,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlInt32 operator -(System.Data.SqlTypes.SqlInt32 x) { throw null; } public static System.Data.SqlTypes.SqlInt32 Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlInt32 Subtract(System.Data.SqlTypes.SqlInt32 x, System.Data.SqlTypes.SqlInt32 y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlBoolean ToSqlBoolean() { throw null; } @@ -3156,10 +3199,10 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlInt64 BitwiseAnd(System.Data.SqlTypes.SqlInt64 x, System.Data.SqlTypes.SqlInt64 y) { throw null; } public static System.Data.SqlTypes.SqlInt64 BitwiseOr(System.Data.SqlTypes.SqlInt64 x, System.Data.SqlTypes.SqlInt64 y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlInt64 value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlInt64 Divide(System.Data.SqlTypes.SqlInt64 x, System.Data.SqlTypes.SqlInt64 y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlInt64 x, System.Data.SqlTypes.SqlInt64 y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlInt64 x, System.Data.SqlTypes.SqlInt64 y) { throw null; } @@ -3200,7 +3243,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlInt64 operator -(System.Data.SqlTypes.SqlInt64 x) { throw null; } public static System.Data.SqlTypes.SqlInt64 Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlInt64 Subtract(System.Data.SqlTypes.SqlInt64 x, System.Data.SqlTypes.SqlInt64 y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlBoolean ToSqlBoolean() { throw null; } @@ -3231,10 +3274,10 @@ namespace System.Data.SqlTypes public decimal Value { get { throw null; } } public static System.Data.SqlTypes.SqlMoney Add(System.Data.SqlTypes.SqlMoney x, System.Data.SqlTypes.SqlMoney y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlMoney value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlMoney Divide(System.Data.SqlTypes.SqlMoney x, System.Data.SqlTypes.SqlMoney y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlMoney x, System.Data.SqlTypes.SqlMoney y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlMoney x, System.Data.SqlTypes.SqlMoney y) { throw null; } @@ -3269,7 +3312,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlMoney operator -(System.Data.SqlTypes.SqlMoney x) { throw null; } public static System.Data.SqlTypes.SqlMoney Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlMoney Subtract(System.Data.SqlTypes.SqlMoney x, System.Data.SqlTypes.SqlMoney y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public decimal ToDecimal() { throw null; } @@ -3290,14 +3333,14 @@ namespace System.Data.SqlTypes public sealed partial class SqlNotFilledException : System.Data.SqlTypes.SqlTypeException { public SqlNotFilledException() { } - public SqlNotFilledException(string message) { } - public SqlNotFilledException(string message, System.Exception e) { } + public SqlNotFilledException(string? message) { } + public SqlNotFilledException(string? message, System.Exception? e) { } } public sealed partial class SqlNullValueException : System.Data.SqlTypes.SqlTypeException { public SqlNullValueException() { } - public SqlNullValueException(string message) { } - public SqlNullValueException(string message, System.Exception e) { } + public SqlNullValueException(string? message) { } + public SqlNullValueException(string? message, System.Exception? e) { } } [System.Xml.Serialization.XmlSchemaProviderAttribute("GetXsdType")] public partial struct SqlSingle : System.Data.SqlTypes.INullable, System.IComparable, System.Xml.Serialization.IXmlSerializable @@ -3313,10 +3356,10 @@ namespace System.Data.SqlTypes public float Value { get { throw null; } } public static System.Data.SqlTypes.SqlSingle Add(System.Data.SqlTypes.SqlSingle x, System.Data.SqlTypes.SqlSingle y) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlSingle value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlSingle Divide(System.Data.SqlTypes.SqlSingle x, System.Data.SqlTypes.SqlSingle y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlSingle x, System.Data.SqlTypes.SqlSingle y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlSingle x, System.Data.SqlTypes.SqlSingle y) { throw null; } @@ -3349,7 +3392,7 @@ namespace System.Data.SqlTypes public static System.Data.SqlTypes.SqlSingle operator -(System.Data.SqlTypes.SqlSingle x) { throw null; } public static System.Data.SqlTypes.SqlSingle Parse(string s) { throw null; } public static System.Data.SqlTypes.SqlSingle Subtract(System.Data.SqlTypes.SqlSingle x, System.Data.SqlTypes.SqlSingle y) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } public System.Data.SqlTypes.SqlBoolean ToSqlBoolean() { throw null; } @@ -3377,11 +3420,11 @@ namespace System.Data.SqlTypes public static readonly System.Data.SqlTypes.SqlString Null; public SqlString(int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions, byte[] data) { throw null; } public SqlString(int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions, byte[] data, bool fUnicode) { throw null; } - public SqlString(int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions, byte[] data, int index, int count) { throw null; } - public SqlString(int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions, byte[] data, int index, int count, bool fUnicode) { throw null; } - public SqlString(string data) { throw null; } - public SqlString(string data, int lcid) { throw null; } - public SqlString(string data, int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions) { throw null; } + public SqlString(int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions, byte[]? data, int index, int count) { throw null; } + public SqlString(int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions, byte[]? data, int index, int count, bool fUnicode) { throw null; } + public SqlString(string? data) { throw null; } + public SqlString(string? data, int lcid) { throw null; } + public SqlString(string? data, int lcid, System.Data.SqlTypes.SqlCompareOptions compareOptions) { throw null; } public System.Globalization.CompareInfo CompareInfo { get { throw null; } } public System.Globalization.CultureInfo CultureInfo { get { throw null; } } public bool IsNull { get { throw null; } } @@ -3392,13 +3435,13 @@ namespace System.Data.SqlTypes public System.Data.SqlTypes.SqlString Clone() { throw null; } public static System.Globalization.CompareOptions CompareOptionsFromSqlCompareOptions(System.Data.SqlTypes.SqlCompareOptions compareOptions) { throw null; } public int CompareTo(System.Data.SqlTypes.SqlString value) { throw null; } - public int CompareTo(object value) { throw null; } + public int CompareTo(object? value) { throw null; } public static System.Data.SqlTypes.SqlString Concat(System.Data.SqlTypes.SqlString x, System.Data.SqlTypes.SqlString y) { throw null; } public static System.Data.SqlTypes.SqlBoolean Equals(System.Data.SqlTypes.SqlString x, System.Data.SqlTypes.SqlString y) { throw null; } - public override bool Equals(object value) { throw null; } + public override bool Equals(object? value) { throw null; } public override int GetHashCode() { throw null; } - public byte[] GetNonUnicodeBytes() { throw null; } - public byte[] GetUnicodeBytes() { throw null; } + public byte[]? GetNonUnicodeBytes() { throw null; } + public byte[]? GetUnicodeBytes() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThan(System.Data.SqlTypes.SqlString x, System.Data.SqlTypes.SqlString y) { throw null; } public static System.Data.SqlTypes.SqlBoolean GreaterThanOrEqual(System.Data.SqlTypes.SqlString x, System.Data.SqlTypes.SqlString y) { throw null; } @@ -3444,28 +3487,28 @@ namespace System.Data.SqlTypes public sealed partial class SqlTruncateException : System.Data.SqlTypes.SqlTypeException { public SqlTruncateException() { } - public SqlTruncateException(string message) { } - public SqlTruncateException(string message, System.Exception e) { } + public SqlTruncateException(string? message) { } + public SqlTruncateException(string? message, System.Exception? e) { } } public partial class SqlTypeException : System.SystemException { public SqlTypeException() { } protected SqlTypeException(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext sc) { } - public SqlTypeException(string message) { } - public SqlTypeException(string message, System.Exception e) { } + public SqlTypeException(string? message) { } + public SqlTypeException(string? message, System.Exception? e) { } } [System.Xml.Serialization.XmlSchemaProviderAttribute("GetXsdType")] public sealed partial class SqlXml : System.Data.SqlTypes.INullable, System.Xml.Serialization.IXmlSerializable { public SqlXml() { } - public SqlXml(System.IO.Stream value) { } - public SqlXml(System.Xml.XmlReader value) { } + public SqlXml(System.IO.Stream? value) { } + public SqlXml(System.Xml.XmlReader? value) { } public bool IsNull { get { throw null; } } public static System.Data.SqlTypes.SqlXml Null { get { throw null; } } public string Value { get { throw null; } } public System.Xml.XmlReader CreateReader() { throw null; } public static System.Xml.XmlQualifiedName GetXsdType(System.Xml.Schema.XmlSchemaSet schemaSet) { throw null; } - System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } + System.Xml.Schema.XmlSchema? System.Xml.Serialization.IXmlSerializable.GetSchema() { throw null; } void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader r) { } void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { } } @@ -3476,6 +3519,7 @@ namespace System.Data.SqlTypes UnmanagedBuffer = 2, } } +#nullable disable namespace System.Xml { [System.ObsoleteAttribute("XmlDataDocument class will be removed in a future release.")] @@ -3498,3 +3542,4 @@ namespace System.Xml public override void Load(System.Xml.XmlReader reader) { } } } +#nullable enable diff --git a/src/libraries/System.Data.Common/ref/System.Data.Common.csproj b/src/libraries/System.Data.Common/ref/System.Data.Common.csproj index f2001f8..ab75121 100644 --- a/src/libraries/System.Data.Common/ref/System.Data.Common.csproj +++ b/src/libraries/System.Data.Common/ref/System.Data.Common.csproj @@ -2,6 +2,7 @@ $(NoWarn);0618 $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Data.Common/src/System.Data.Common.csproj b/src/libraries/System.Data.Common/src/System.Data.Common.csproj index 2009104..cbde684 100644 --- a/src/libraries/System.Data.Common/src/System.Data.Common.csproj +++ b/src/libraries/System.Data.Common/src/System.Data.Common.csproj @@ -3,6 +3,7 @@ System.Data.Common true $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs b/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs index 5e6b9e2..942a2ac 100644 --- a/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs @@ -34,7 +34,7 @@ namespace System.Data // > 0 (1) : CaseSensitve equal // < 0 (-1) : Case-Insensitive Equal // = 0 : Not Equal - internal int NamesEqual(string s1, string s2, bool fCaseSensitive, CultureInfo locale) + internal int NamesEqual(string? s1, string? s2, bool fCaseSensitive, CultureInfo locale) { if (fCaseSensitive) { @@ -54,6 +54,6 @@ namespace System.Data [Browsable(false)] public object SyncRoot => this; - protected virtual ArrayList List => null; + protected virtual ArrayList List => null!; // Always overridden by implementations and non-null } } diff --git a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs index 629f2fc..60c883d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs @@ -51,7 +51,7 @@ namespace System.Data typeof(SqlChars), typeof(SqlXml) }; - private StandardValuesCollection _values; + private StandardValuesCollection? _values; public ColumnTypeConverter() { } @@ -65,7 +65,7 @@ namespace System.Data /// /// Converts the given value object to the specified destination type. /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object? ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object? value, Type destinationType) { if (destinationType == null) { @@ -93,10 +93,10 @@ namespace System.Data if (value is Type || value is string) { - MethodInfo method = typeof(Type).GetMethod("GetType", new Type[] { typeof(string) }); + MethodInfo method = typeof(Type).GetMethod("GetType", new Type[] { typeof(string) })!; if (method != null) { - return new InstanceDescriptor(method, new object[] { ((Type)newValue).AssemblyQualifiedName }); + return new InstanceDescriptor(method, new object[] { ((Type)newValue).AssemblyQualifiedName! }); } } } @@ -133,7 +133,7 @@ namespace System.Data { if (_values == null) { - object[] objTypes; + object[]? objTypes; if (s_types != null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs b/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs index 409eb74..619b5ba 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable nullability as part of annotation System.Data.{Odbc,OleDb} +#nullable disable + using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs index bb5eb07..fdff3ed 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/BigIntegerStorage.cs @@ -9,7 +9,7 @@ namespace System.Data.Common { internal sealed class BigIntegerStorage : DataStorage { - private BigInteger[] _values; + private BigInteger[] _values = default!; // Late-initialized internal BigIntegerStorage(DataColumn column) : base(column, typeof(BigInteger), BigInteger.Zero, StorageType.BigInteger) @@ -38,7 +38,7 @@ namespace System.Data.Common return valueNo1.CompareTo(valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); Debug.Assert(null != value, "null value"); @@ -91,7 +91,7 @@ namespace System.Data.Common else { throw ExceptionBuilder.ConvertFailed(typeof(System.Numerics.BigInteger), type); } } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs index 57410dd..99e6ce4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/BooleanStorage.cs @@ -11,7 +11,7 @@ namespace System.Data.Common { private const bool defaultValue = false; - private bool[] _values; + private bool[] _values = default!; // Late-initialized internal BooleanStorage(DataColumn column) : base(column, typeof(bool), defaultValue, StorageType.Boolean) @@ -57,12 +57,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -89,7 +89,7 @@ namespace System.Data.Common return valueNo1.CompareTo(valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); Debug.Assert(null != value, "null value"); @@ -111,7 +111,7 @@ namespace System.Data.Common return valueNo1.CompareTo((bool)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs index 8c051d3..1fd8b9d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ByteStorage.cs @@ -11,7 +11,7 @@ namespace System.Data.Common { private const byte defaultValue = 0; - private byte[] _values; + private byte[] _values = default!; // Late-initialized internal ByteStorage(DataColumn column) : base(column, typeof(byte), defaultValue, StorageType.Byte) { @@ -129,12 +129,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -161,7 +161,7 @@ namespace System.Data.Common return valueNo1.CompareTo(valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -183,7 +183,7 @@ namespace System.Data.Common return valueNo1.CompareTo((byte)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs index f61abb1..72027fe 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/CharStorage.cs @@ -11,7 +11,7 @@ namespace System.Data.Common { private const char defaultValue = '\0'; - private char[] _values; + private char[] _values = default!; // Late-initialized internal CharStorage(DataColumn column) : base(column, typeof(char), defaultValue, StorageType.Char) { @@ -56,12 +56,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -88,7 +88,7 @@ namespace System.Data.Common return valueNo1.CompareTo(valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -110,7 +110,7 @@ namespace System.Data.Common return valueNo1.CompareTo((char)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs index 06bf2e0..72a5d8d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -22,20 +23,20 @@ namespace System.Data.Common private const string AlternativeOriginalPrefix2 = "ORIGINAL"; private const string AlternativeIsNullPrefix2 = "ISNULL"; - private string _originalPrefix; - private string _isNullPrefix; + private string? _originalPrefix; + private string? _isNullPrefix; private readonly Regex _parameterNameParser; private readonly DbCommandBuilder _dbCommandBuilder; - private readonly string[] _baseParameterNames; - private readonly string[] _originalParameterNames; - private readonly string[] _nullParameterNames; + private readonly string?[] _baseParameterNames; + private readonly string?[] _originalParameterNames; + private readonly string?[] _nullParameterNames; private readonly bool[] _isMutatedName; private readonly int _count; private int _genericParameterCount; private readonly int _adjustedParameterNameMaxLength; - internal ParameterNames(DbCommandBuilder dbCommandBuilder, DbSchemaRow[] schemaRows) + internal ParameterNames(DbCommandBuilder dbCommandBuilder, DbSchemaRow?[] schemaRows) { _dbCommandBuilder = dbCommandBuilder; _baseParameterNames = new string[schemaRows.Length]; @@ -43,7 +44,7 @@ namespace System.Data.Common _nullParameterNames = new string[schemaRows.Length]; _isMutatedName = new bool[schemaRows.Length]; _count = schemaRows.Length; - _parameterNameParser = new Regex(_dbCommandBuilder.ParameterNamePattern, RegexOptions.ExplicitCapture | RegexOptions.Singleline); + _parameterNameParser = new Regex(_dbCommandBuilder.ParameterNamePattern!, RegexOptions.ExplicitCapture | RegexOptions.Singleline); SetAndValidateNamePrefixes(); _adjustedParameterNameMaxLength = GetAdjustedParameterNameMaxLength(); @@ -55,12 +56,13 @@ namespace System.Data.Common // for (int i = 0; i < schemaRows.Length; i++) { - if (null == schemaRows[i]) + var schemaRow = schemaRows[i]; + if (null == schemaRow) { continue; } bool isMutatedName = false; - string columnName = schemaRows[i].ColumnName; + string columnName = schemaRow.ColumnName; // all names that start with original- or isNullPrefix are invalid if (null != _originalPrefix) @@ -116,7 +118,7 @@ namespace System.Data.Common if (null != _isNullPrefix) { // don't bother generating an 'IsNull' name if it's not used - if (schemaRows[i].AllowDBNull) + if (schemaRows[i]!.AllowDBNull) { _nullParameterNames[i] = _isNullPrefix + _baseParameterNames[i]; } @@ -167,17 +169,17 @@ namespace System.Data.Common { for (int i = 0; i < _baseParameterNames.Length; i++) { - if (null != _baseParameterNames[i]) + if (_baseParameterNames[i] is { } baseParameterName) { - _baseParameterNames[i] = _dbCommandBuilder.GetParameterName(_baseParameterNames[i]); + _baseParameterNames[i] = _dbCommandBuilder.GetParameterName(baseParameterName); } - if (null != _originalParameterNames[i]) + if (_originalParameterNames[i] is { } originalParameterName) { - _originalParameterNames[i] = _dbCommandBuilder.GetParameterName(_originalParameterNames[i]); + _originalParameterNames[i] = _dbCommandBuilder.GetParameterName(originalParameterName); } - if (null != _nullParameterNames[i]) + if (_nullParameterNames[i] is { } nullParameterName) { - _nullParameterNames[i] = _dbCommandBuilder.GetParameterName(_nullParameterNames[i]); + _nullParameterNames[i] = _dbCommandBuilder.GetParameterName(nullParameterName); } } } @@ -186,7 +188,7 @@ namespace System.Data.Common { for (int i = 0; i < _count - 1; i++) { - string name = _baseParameterNames[i]; + string? name = _baseParameterNames[i]; if (null != name) { for (int j = i + 1; j < _count; j++) @@ -205,7 +207,7 @@ namespace System.Data.Common } // Generates parameternames that couldn't be generated from columnname - internal void GenerateMissingNames(DbSchemaRow[] schemaRows) + internal void GenerateMissingNames(DbSchemaRow?[] schemaRows) { // foreach name in base names // if base name is null @@ -217,7 +219,7 @@ namespace System.Data.Common // loop while name occurs in base names // end for // end foreach - string name; + string? name; for (int i = 0; i < _baseParameterNames.Length; i++) { name = _baseParameterNames[i]; @@ -226,7 +228,7 @@ namespace System.Data.Common _baseParameterNames[i] = GetNextGenericParameterName(); _originalParameterNames[i] = GetNextGenericParameterName(); // don't bother generating an 'IsNull' name if it's not used - if ((null != schemaRows[i]) && schemaRows[i].AllowDBNull) + if (schemaRows[i] is { } schemaRow && schemaRow.AllowDBNull) { _nullParameterNames[i] = GetNextGenericParameterName(); } @@ -264,15 +266,15 @@ namespace System.Data.Common return name; } - internal string GetBaseParameterName(int index) + internal string? GetBaseParameterName(int index) { return (_baseParameterNames[index]); } - internal string GetOriginalParameterName(int index) + internal string? GetOriginalParameterName(int index) { return (_originalParameterNames[index]); } - internal string GetNullParameterName(int index) + internal string? GetNullParameterName(int index) { return (_nullParameterNames[index]); } @@ -301,11 +303,11 @@ namespace System.Data.Common private const string And = " AND "; private const string Or = " OR "; - private DbDataAdapter _dataAdapter; + private DbDataAdapter? _dataAdapter; - private DbCommand _insertCommand; - private DbCommand _updateCommand; - private DbCommand _deleteCommand; + private DbCommand? _insertCommand; + private DbCommand? _updateCommand; + private DbCommand? _deleteCommand; private MissingMappingAction _missingMappingAction; @@ -313,21 +315,21 @@ namespace System.Data.Common private bool _setAllValues; private bool _hasPartialPrimaryKey; - private DataTable _dbSchemaTable; - private DbSchemaRow[] _dbSchemaRows; - private string[] _sourceColumnNames; - private ParameterNames _parameterNames; + private DataTable? _dbSchemaTable; + private DbSchemaRow?[]? _dbSchemaRows; + private string[]? _sourceColumnNames; + private ParameterNames? _parameterNames; - private string _quotedBaseTableName; + private string? _quotedBaseTableName; // quote strings to use around SQL object names private CatalogLocation _catalogLocation = CatalogLocation.Start; - private string _catalogSeparator = NameSeparator; - private string _schemaSeparator = NameSeparator; - private string _quotePrefix = string.Empty; - private string _quoteSuffix = string.Empty; - private string _parameterNamePattern; - private string _parameterMarkerFormat; + private string? _catalogSeparator = NameSeparator; + private string? _schemaSeparator = NameSeparator; + private string? _quotePrefix = string.Empty; + private string? _quoteSuffix = string.Empty; + private string? _parameterNamePattern; + private string? _parameterMarkerFormat; private int _parameterNameMaxLength; protected DbCommandBuilder() : base() @@ -382,11 +384,12 @@ namespace System.Data.Common } [DefaultValueAttribute(DbCommandBuilder.NameSeparator)] + [AllowNull] public virtual string CatalogSeparator { get { - string catalogSeparator = _catalogSeparator; + string? catalogSeparator = _catalogSeparator; return (((null != catalogSeparator) && (0 < catalogSeparator.Length)) ? catalogSeparator : NameSeparator); } set @@ -401,7 +404,7 @@ namespace System.Data.Common [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public DbDataAdapter DataAdapter + public DbDataAdapter? DataAdapter { get { @@ -437,7 +440,7 @@ namespace System.Data.Common } } - internal string ParameterNamePattern + internal string? ParameterNamePattern { get { @@ -445,7 +448,7 @@ namespace System.Data.Common } } - private string QuotedBaseTableName + private string? QuotedBaseTableName { get { @@ -454,6 +457,7 @@ namespace System.Data.Common } [DefaultValueAttribute("")] + [AllowNull] public virtual string QuotePrefix { get { return _quotePrefix ?? string.Empty; } @@ -468,11 +472,12 @@ namespace System.Data.Common } [DefaultValueAttribute("")] + [AllowNull] public virtual string QuoteSuffix { get { - string quoteSuffix = _quoteSuffix; + string? quoteSuffix = _quoteSuffix; return ((null != quoteSuffix) ? quoteSuffix : string.Empty); } set @@ -487,11 +492,12 @@ namespace System.Data.Common [DefaultValueAttribute(DbCommandBuilder.NameSeparator)] + [AllowNull] public virtual string SchemaSeparator { get { - string schemaSeparator = _schemaSeparator; + string? schemaSeparator = _schemaSeparator; return (((null != schemaSeparator) && (0 < schemaSeparator.Length)) ? schemaSeparator : NameSeparator); } set @@ -517,7 +523,7 @@ namespace System.Data.Common } } - private DbCommand InsertCommand + private DbCommand? InsertCommand { get { @@ -529,7 +535,7 @@ namespace System.Data.Common } } - private DbCommand UpdateCommand + private DbCommand? UpdateCommand { get { @@ -541,7 +547,7 @@ namespace System.Data.Common } } - private DbCommand DeleteCommand + private DbCommand? DeleteCommand { get { @@ -553,7 +559,7 @@ namespace System.Data.Common } } - private void BuildCache(bool closeConnection, DataRow dataRow, bool useColumnsForParameterNames) + private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsForParameterNames) { // Don't bother building the cache if it's done already; wait for // the user to call RefreshSchema first. @@ -561,10 +567,10 @@ namespace System.Data.Common { return; } - DataTable schemaTable = null; + DataTable? schemaTable = null; DbCommand srcCommand = GetSelectCommand(); - DbConnection connection = srcCommand.Connection; + DbConnection? connection = srcCommand.Connection; if (null == connection) { throw ADP.MissingSourceCommandConnection(); @@ -623,13 +629,13 @@ namespace System.Data.Common _dbSchemaTable = schemaTable; - DbSchemaRow[] schemaRows = _dbSchemaRows; + DbSchemaRow?[] schemaRows = _dbSchemaRows!; string[] srcColumnNames = new string[schemaRows.Length]; for (int i = 0; i < schemaRows.Length; ++i) { - if (null != schemaRows[i]) + if (schemaRows[i] is { } schemaRow) { - srcColumnNames[i] = schemaRows[i].ColumnName; + srcColumnNames[i] = schemaRow.ColumnName; } } _sourceColumnNames = srcColumnNames; @@ -650,20 +656,20 @@ namespace System.Data.Common private void BuildInformation(DataTable schemaTable) { - DbSchemaRow[] rows = DbSchemaRow.GetSortedSchemaRows(schemaTable, false); + DbSchemaRow?[]? rows = DbSchemaRow.GetSortedSchemaRows(schemaTable, false); if ((null == rows) || (0 == rows.Length)) { throw ADP.DynamicSQLNoTableInfo(); } - string baseServerName = string.Empty; - string baseCatalogName = string.Empty; - string baseSchemaName = string.Empty; - string baseTableName = null; + string? baseServerName = string.Empty; + string? baseCatalogName = string.Empty; + string? baseSchemaName = string.Empty; + string? baseTableName = null; for (int i = 0; i < rows.Length; ++i) { - DbSchemaRow row = rows[i]; + DbSchemaRow row = rows[i]!; string tableName = row.BaseTableName; if ((null == tableName) || (0 == tableName.Length)) { @@ -774,7 +780,7 @@ namespace System.Data.Common _quotedBaseTableName = builder.ToString(); _hasPartialPrimaryKey = false; - foreach (DbSchemaRow row in rows) + foreach (DbSchemaRow? row in rows) { if ((null != row) && (row.IsKey || row.IsUnique) && !row.IsLong && !row.IsRowVersion && row.IsHidden) { @@ -785,7 +791,7 @@ namespace System.Data.Common _dbSchemaRows = rows; } - private DbCommand BuildDeleteCommand(DataTableMapping mappings, DataRow dataRow) + private DbCommand BuildDeleteCommand(DataTableMapping? mappings, DataRow? dataRow) { DbCommand command = InitializeCommand(DeleteCommand); StringBuilder builder = new StringBuilder(); @@ -805,7 +811,7 @@ namespace System.Data.Common return command; } - private DbCommand BuildInsertCommand(DataTableMapping mappings, DataRow dataRow) + private DbCommand BuildInsertCommand(DataTableMapping? mappings, DataRow? dataRow) { DbCommand command = InitializeCommand(InsertCommand); StringBuilder builder = new StringBuilder(); @@ -818,7 +824,7 @@ namespace System.Data.Common builder.Append(QuotedBaseTableName); // search for the columns in that base table, to be the column clause - DbSchemaRow[] schemaRows = _dbSchemaRows; + DbSchemaRow[] schemaRows = _dbSchemaRows!; string[] parameterName = new string[schemaRows.Length]; for (int i = 0; i < schemaRows.Length; ++i) @@ -828,15 +834,15 @@ namespace System.Data.Common if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInInsertValues(row)) continue; - object currentValue = null; - string sourceColumn = _sourceColumnNames[i]; + object? currentValue = null; + string sourceColumn = _sourceColumnNames![i]; // If we're building a statement for a specific row, then check the // values to see whether the column should be included in the insert // statement or not if ((null != mappings) && (null != dataRow)) { - DataColumn dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); + DataColumn? dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); if (null == dataColumn) continue; @@ -896,7 +902,7 @@ namespace System.Data.Common return command; } - private DbCommand BuildUpdateCommand(DataTableMapping mappings, DataRow dataRow) + private DbCommand? BuildUpdateCommand(DataTableMapping? mappings, DataRow? dataRow) { DbCommand command = InitializeCommand(UpdateCommand); StringBuilder builder = new StringBuilder(); @@ -909,7 +915,7 @@ namespace System.Data.Common builder.Append(QuotedBaseTableName); // search for the columns in that base table, to build the set clause - DbSchemaRow[] schemaRows = _dbSchemaRows; + DbSchemaRow[] schemaRows = _dbSchemaRows!; for (int i = 0; i < schemaRows.Length; ++i) { DbSchemaRow row = schemaRows[i]; @@ -917,15 +923,15 @@ namespace System.Data.Common if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInUpdateSet(row)) continue; - object currentValue = null; - string sourceColumn = _sourceColumnNames[i]; + object? currentValue = null; + string sourceColumn = _sourceColumnNames![i]; // If we're building a statement for a specific row, then check the // values to see whether the column should be included in the update // statement or not if ((null != mappings) && (null != dataRow)) { - DataColumn dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); + DataColumn? dataColumn = GetDataColumn(sourceColumn, mappings, dataRow); if (null == dataColumn) continue; @@ -984,8 +990,8 @@ namespace System.Data.Common } private int BuildWhereClause( - DataTableMapping mappings, - DataRow dataRow, + DataTableMapping? mappings, + DataRow? dataRow, StringBuilder builder, DbCommand command, int parameterCount, @@ -998,7 +1004,7 @@ namespace System.Data.Common builder.Append(Where); builder.Append(LeftParenthesis); - DbSchemaRow[] schemaRows = _dbSchemaRows; + DbSchemaRow[] schemaRows = _dbSchemaRows!; for (int i = 0; i < schemaRows.Length; ++i) { DbSchemaRow row = schemaRows[i]; @@ -1010,8 +1016,8 @@ namespace System.Data.Common builder.Append(beginNewCondition); beginNewCondition = And; - object value = null; - string sourceColumn = _sourceColumnNames[i]; + object? value = null; + string sourceColumn = _sourceColumnNames![i]; string baseColumnName = QuotedColumn(row.BaseColumnName); if ((null != mappings) && (null != dataRow)) @@ -1115,11 +1121,11 @@ namespace System.Data.Common private string CreateParameterForNullTest( DbCommand command, - string parameterName, + string? parameterName, string sourceColumn, DataRowVersion version, int parameterCount, - object value, + object? value, DbSchemaRow row, StatementType statementType, bool whereClause @@ -1168,11 +1174,11 @@ namespace System.Data.Common private string CreateParameterForValue( DbCommand command, - string parameterName, + string? parameterName, string sourceColumn, DataRowVersion version, int parameterCount, - object value, + object? value, DbSchemaRow row, StatementType statementType, bool whereClause @@ -1227,15 +1233,15 @@ namespace System.Data.Common base.Dispose(disposing); // notify base classes } - private DataTableMapping GetTableMapping(DataRow dataRow) + private DataTableMapping? GetTableMapping(DataRow? dataRow) { - DataTableMapping tableMapping = null; + DataTableMapping? tableMapping = null; if (null != dataRow) { DataTable dataTable = dataRow.Table; if (null != dataTable) { - DbDataAdapter adapter = DataAdapter; + DbDataAdapter? adapter = DataAdapter; if (null != adapter) { tableMapping = adapter.GetTableMapping(dataTable); @@ -1250,7 +1256,7 @@ namespace System.Data.Common return tableMapping; } - private string GetBaseParameterName(int index) + private string? GetBaseParameterName(int index) { if (null != _parameterNames) { @@ -1261,7 +1267,7 @@ namespace System.Data.Common return null; } } - private string GetOriginalParameterName(int index) + private string? GetOriginalParameterName(int index) { if (null != _parameterNames) { @@ -1272,7 +1278,7 @@ namespace System.Data.Common return null; } } - private string GetNullParameterName(int index) + private string? GetNullParameterName(int index) { if (null != _parameterNames) { @@ -1286,8 +1292,8 @@ namespace System.Data.Common private DbCommand GetSelectCommand() { - DbCommand select = null; - DbDataAdapter adapter = DataAdapter; + DbCommand? select = null; + DbDataAdapter? adapter = DataAdapter; if (null != adapter) { if (0 == _missingMappingAction) @@ -1312,11 +1318,11 @@ namespace System.Data.Common { return GetInsertCommand(null, useColumnsForParameterNames); } - internal DbCommand GetInsertCommand(DataRow dataRow, bool useColumnsForParameterNames) + internal DbCommand GetInsertCommand(DataRow? dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildInsertCommand(GetTableMapping(dataRow), dataRow); - return InsertCommand; + return InsertCommand!; } public DbCommand GetUpdateCommand() @@ -1327,11 +1333,11 @@ namespace System.Data.Common { return GetUpdateCommand(null, useColumnsForParameterNames); } - internal DbCommand GetUpdateCommand(DataRow dataRow, bool useColumnsForParameterNames) + internal DbCommand GetUpdateCommand(DataRow? dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildUpdateCommand(GetTableMapping(dataRow), dataRow); - return UpdateCommand; + return UpdateCommand!; } public DbCommand GetDeleteCommand() @@ -1342,21 +1348,22 @@ namespace System.Data.Common { return GetDeleteCommand(null, useColumnsForParameterNames); } - internal DbCommand GetDeleteCommand(DataRow dataRow, bool useColumnsForParameterNames) + internal DbCommand GetDeleteCommand(DataRow? dataRow, bool useColumnsForParameterNames) { BuildCache(true, dataRow, useColumnsForParameterNames); BuildDeleteCommand(GetTableMapping(dataRow), dataRow); - return DeleteCommand; + return DeleteCommand!; } - private object GetColumnValue(DataRow row, string columnName, DataTableMapping mappings, DataRowVersion version) + private object? GetColumnValue(DataRow row, string columnName, DataTableMapping mappings, DataRowVersion version) { return GetColumnValue(row, GetDataColumn(columnName, mappings, row), version); } - private object GetColumnValue(DataRow row, DataColumn column, DataRowVersion version) + [return: NotNullIfNotNull("column")] + private object? GetColumnValue(DataRow row, DataColumn? column, DataRowVersion version) { - object value = null; + object? value = null; if (null != column) { value = row[column, version]; @@ -1364,9 +1371,9 @@ namespace System.Data.Common return value; } - private DataColumn GetDataColumn(string columnName, DataTableMapping tablemapping, DataRow row) + private DataColumn? GetDataColumn(string columnName, DataTableMapping tablemapping, DataRow row) { - DataColumn column = null; + DataColumn? column = null; if (!string.IsNullOrEmpty(columnName)) { column = tablemapping.GetDataColumn(columnName, null, row.Table, _missingMappingAction, MissingSchemaAction.Error); @@ -1440,12 +1447,12 @@ namespace System.Data.Common } } - protected virtual DbCommand InitializeCommand(DbCommand command) + protected virtual DbCommand InitializeCommand(DbCommand? command) { if (null == command) { DbCommand select = GetSelectCommand(); - command = select.Connection.CreateCommand(); + command = select.Connection!.CreateCommand(); /*if (null == command) { // CONSIDER: throw exception }*/ @@ -1478,7 +1485,7 @@ namespace System.Data.Common _sourceColumnNames = null; _quotedBaseTableName = null; - DbDataAdapter adapter = DataAdapter; + DbDataAdapter? adapter = DataAdapter; if (null != adapter) { if (InsertCommand == adapter.InsertCommand) @@ -1494,7 +1501,7 @@ namespace System.Data.Common adapter.DeleteCommand = null; } } - DbCommand command; + DbCommand? command; if (null != (command = InsertCommand)) { command.Dispose(); @@ -1531,7 +1538,7 @@ namespace System.Data.Common if (UpdateStatus.Continue == rowUpdatingEvent.Status) { StatementType stmtType = rowUpdatingEvent.StatementType; - DbCommand command = (DbCommand)rowUpdatingEvent.Command; + DbCommand? command = (DbCommand?)rowUpdatingEvent.Command; if (null != command) { @@ -1555,11 +1562,11 @@ namespace System.Data.Common if (command != rowUpdatingEvent.Command) { - command = (DbCommand)rowUpdatingEvent.Command; + command = (DbCommand?)rowUpdatingEvent.Command; if ((null != command) && (null == command.Connection)) { - DbDataAdapter adapter = DataAdapter; - DbCommand select = ((null != adapter) ? adapter.SelectCommand : null); + DbDataAdapter? adapter = DataAdapter; + DbCommand? select = ((null != adapter) ? adapter.SelectCommand : null); if (null != select) { command.Connection = select.Connection; @@ -1589,7 +1596,7 @@ namespace System.Data.Common DataRow datarow = rowUpdatingEvent.Row; BuildCache(false, datarow, false); - DbCommand command; + DbCommand? command; switch (rowUpdatingEvent.StatementType) { case StatementType.Insert: diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs index 698d4e0..438433e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs @@ -14,7 +14,7 @@ namespace System.Data.Common internal static DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool returnProviderSpecificTypes) { - DataColumn sortindex = dataTable.Columns[SchemaMappingUnsortedIndex]; + DataColumn? sortindex = dataTable.Columns[SchemaMappingUnsortedIndex]; if (null == sortindex) { sortindex = new DataColumn(SchemaMappingUnsortedIndex, typeof(int)); @@ -62,7 +62,7 @@ namespace System.Data.Common object value = _dataRow[_schemaTable.ColumnName, DataRowVersion.Default]; if (!Convert.IsDBNull(value)) { - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } return string.Empty; } @@ -91,7 +91,7 @@ namespace System.Data.Common object value = _dataRow[_schemaTable.BaseColumnName, DataRowVersion.Default]; if (!Convert.IsDBNull(value)) { - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } return string.Empty; @@ -107,7 +107,7 @@ namespace System.Data.Common object value = _dataRow[_schemaTable.BaseServerName, DataRowVersion.Default]; if (!Convert.IsDBNull(value)) { - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } return string.Empty; @@ -124,7 +124,7 @@ namespace System.Data.Common object value = _dataRow[_schemaTable.BaseCatalogName, DataRowVersion.Default]; if (!Convert.IsDBNull(value)) { - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } return string.Empty; @@ -140,7 +140,7 @@ namespace System.Data.Common object value = _dataRow[_schemaTable.BaseSchemaName, DataRowVersion.Default]; if (!Convert.IsDBNull(value)) { - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } return string.Empty; @@ -156,7 +156,7 @@ namespace System.Data.Common object value = _dataRow[_schemaTable.BaseTableName, DataRowVersion.Default]; if (!Convert.IsDBNull(value)) { - return Convert.ToString(value, CultureInfo.InvariantCulture); + return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } return string.Empty; @@ -291,7 +291,7 @@ namespace System.Data.Common } } - internal Type DataType + internal Type? DataType { get { @@ -327,7 +327,7 @@ namespace System.Data.Common { get { - return (int)_dataRow[_schemaTable.UnsortedIndex, DataRowVersion.Default]; + return (int)_dataRow[_schemaTable.UnsortedIndex!, DataRowVersion.Default]; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs index e099b7c..cbe7725 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaTable.cs @@ -56,7 +56,7 @@ namespace System.Data.Common internal DataTable _dataTable; private readonly DataColumnCollection _columns; - private readonly DataColumn[] _columnCache = new DataColumn[s_DBCOLUMN_NAME.Length]; + private readonly DataColumn?[] _columnCache = new DataColumn[s_DBCOLUMN_NAME.Length]; private readonly bool _returnProviderSpecificTypes; internal DbSchemaTable(DataTable dataTable, bool returnProviderSpecificTypes) @@ -66,27 +66,27 @@ namespace System.Data.Common _returnProviderSpecificTypes = returnProviderSpecificTypes; } - internal DataColumn ColumnName { get { return CachedDataColumn(ColumnEnum.ColumnName); } } - internal DataColumn Size { get { return CachedDataColumn(ColumnEnum.ColumnSize); } } - internal DataColumn BaseServerName { get { return CachedDataColumn(ColumnEnum.BaseServerName); } } - internal DataColumn BaseColumnName { get { return CachedDataColumn(ColumnEnum.BaseColumnName); } } - internal DataColumn BaseTableName { get { return CachedDataColumn(ColumnEnum.BaseTableName); } } - internal DataColumn BaseCatalogName { get { return CachedDataColumn(ColumnEnum.BaseCatalogName); } } - internal DataColumn BaseSchemaName { get { return CachedDataColumn(ColumnEnum.BaseSchemaName); } } - internal DataColumn IsAutoIncrement { get { return CachedDataColumn(ColumnEnum.IsAutoIncrement); } } - internal DataColumn IsUnique { get { return CachedDataColumn(ColumnEnum.IsUnique); } } - internal DataColumn IsKey { get { return CachedDataColumn(ColumnEnum.IsKey); } } - internal DataColumn IsRowVersion { get { return CachedDataColumn(ColumnEnum.IsRowVersion); } } + internal DataColumn? ColumnName { get { return CachedDataColumn(ColumnEnum.ColumnName); } } + internal DataColumn? Size { get { return CachedDataColumn(ColumnEnum.ColumnSize); } } + internal DataColumn? BaseServerName { get { return CachedDataColumn(ColumnEnum.BaseServerName); } } + internal DataColumn? BaseColumnName { get { return CachedDataColumn(ColumnEnum.BaseColumnName); } } + internal DataColumn? BaseTableName { get { return CachedDataColumn(ColumnEnum.BaseTableName); } } + internal DataColumn? BaseCatalogName { get { return CachedDataColumn(ColumnEnum.BaseCatalogName); } } + internal DataColumn? BaseSchemaName { get { return CachedDataColumn(ColumnEnum.BaseSchemaName); } } + internal DataColumn? IsAutoIncrement { get { return CachedDataColumn(ColumnEnum.IsAutoIncrement); } } + internal DataColumn? IsUnique { get { return CachedDataColumn(ColumnEnum.IsUnique); } } + internal DataColumn? IsKey { get { return CachedDataColumn(ColumnEnum.IsKey); } } + internal DataColumn? IsRowVersion { get { return CachedDataColumn(ColumnEnum.IsRowVersion); } } - internal DataColumn AllowDBNull { get { return CachedDataColumn(ColumnEnum.AllowDBNull); } } - internal DataColumn IsExpression { get { return CachedDataColumn(ColumnEnum.IsExpression); } } - internal DataColumn IsHidden { get { return CachedDataColumn(ColumnEnum.IsHidden); } } - internal DataColumn IsLong { get { return CachedDataColumn(ColumnEnum.IsLong); } } - internal DataColumn IsReadOnly { get { return CachedDataColumn(ColumnEnum.IsReadOnly); } } + internal DataColumn? AllowDBNull { get { return CachedDataColumn(ColumnEnum.AllowDBNull); } } + internal DataColumn? IsExpression { get { return CachedDataColumn(ColumnEnum.IsExpression); } } + internal DataColumn? IsHidden { get { return CachedDataColumn(ColumnEnum.IsHidden); } } + internal DataColumn? IsLong { get { return CachedDataColumn(ColumnEnum.IsLong); } } + internal DataColumn? IsReadOnly { get { return CachedDataColumn(ColumnEnum.IsReadOnly); } } - internal DataColumn UnsortedIndex { get { return CachedDataColumn(ColumnEnum.SchemaMappingUnsortedIndex); } } + internal DataColumn? UnsortedIndex { get { return CachedDataColumn(ColumnEnum.SchemaMappingUnsortedIndex); } } - internal DataColumn DataType + internal DataColumn? DataType { get { @@ -98,14 +98,14 @@ namespace System.Data.Common } } - private DataColumn CachedDataColumn(ColumnEnum column) + private DataColumn? CachedDataColumn(ColumnEnum column) { return CachedDataColumn(column, column); } - private DataColumn CachedDataColumn(ColumnEnum column, ColumnEnum column2) + private DataColumn? CachedDataColumn(ColumnEnum column, ColumnEnum column2) { - DataColumn dataColumn = _columnCache[(int)column]; + DataColumn? dataColumn = _columnCache[(int)column]; if (null == dataColumn) { int index = _columns.IndexOf(s_DBCOLUMN_NAME[(int)column]); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs index ec66acf..48e4492 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Data.ProviderBase; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data.Common @@ -23,7 +24,7 @@ namespace System.Data.Common private MissingMappingAction _missingMappingAction = System.Data.MissingMappingAction.Passthrough; private MissingSchemaAction _missingSchemaAction = System.Data.MissingSchemaAction.Add; - private DataTableMappingCollection _tableMappings; + private DataTableMappingCollection? _tableMappings; private static int s_objectTypeCount; // Bid counter internal readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); @@ -165,7 +166,7 @@ namespace System.Data.Common { get { - DataTableMappingCollection mappings = _tableMappings; + DataTableMappingCollection? mappings = _tableMappings; if (null == mappings) { mappings = CreateTableMappings(); @@ -185,7 +186,7 @@ namespace System.Data.Common protected bool HasTableMappings() => ((null != _tableMappings) && (0 < TableMappings.Count)); - public event FillErrorEventHandler FillError + public event FillErrorEventHandler? FillError { add { @@ -201,7 +202,7 @@ namespace System.Data.Common [Obsolete("CloneInternals() has been deprecated. Use the DataAdapter(DataAdapter from) constructor. https://go.microsoft.com/fwlink/?linkid=14202")] protected virtual DataAdapter CloneInternals() { - DataAdapter clone = (DataAdapter)Activator.CreateInstance(GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); + DataAdapter clone = (DataAdapter)Activator.CreateInstance(GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null)!; clone.CloneFrom(this); return clone; } @@ -272,7 +273,8 @@ namespace System.Data.Common throw ADP.FillRequires(nameof(dataReader)); } // user must Close/Dispose of the dataReader - object value = FillSchemaFromReader(dataSet, null, schemaType, srcTable, dataReader); + // Never returns null if dataSet is non-null + object value = FillSchemaFromReader(dataSet, null, schemaType, srcTable, dataReader)!; return (DataTable[])value; } finally @@ -281,7 +283,7 @@ namespace System.Data.Common } } - protected virtual DataTable FillSchema(DataTable dataTable, SchemaType schemaType, IDataReader dataReader) + protected virtual DataTable? FillSchema(DataTable dataTable, SchemaType schemaType, IDataReader dataReader) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTable, schemaType, dataReader", ObjectID); try @@ -300,8 +302,8 @@ namespace System.Data.Common } // user must Close/Dispose of the dataReader // user will have to call NextResult to access remaining results - object value = FillSchemaFromReader(null, dataTable, schemaType, null, dataReader); - return (DataTable)value; + object? value = FillSchemaFromReader(null, dataTable, schemaType, null, dataReader); + return (DataTable?)value; } finally { @@ -309,9 +311,9 @@ namespace System.Data.Common } } - internal object FillSchemaFromReader(DataSet dataset, DataTable datatable, SchemaType schemaType, string srcTable, IDataReader dataReader) + internal object? FillSchemaFromReader(DataSet? dataset, DataTable? datatable, SchemaType schemaType, string? srcTable, IDataReader dataReader) { - DataTable[] dataTables = null; + DataTable[]? dataTables = null; int schemaCount = 0; do { @@ -322,10 +324,10 @@ namespace System.Data.Common { continue; } - string tmp = null; + string? tmp = null; if (null != dataset) { - tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount); + tmp = DataAdapter.GetSourceTableName(srcTable!, schemaCount); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) } @@ -349,7 +351,7 @@ namespace System.Data.Common } } while (dataReader.NextResult()); // FillSchema does not capture errors for FillError event - object value = dataTables; + object? value = dataTables; if ((null == value) && (null == datatable)) { value = Array.Empty(); @@ -428,7 +430,7 @@ namespace System.Data.Common int result = 0; bool enforceContraints = false; - DataSet commonDataSet = dataTables[0].DataSet; + DataSet? commonDataSet = dataTables[0].DataSet; try { if (null != commonDataSet) @@ -488,7 +490,7 @@ namespace System.Data.Common { if (enforceContraints) { - commonDataSet.EnforceConstraints = true; + commonDataSet!.EnforceConstraints = true; } } return result; @@ -499,7 +501,7 @@ namespace System.Data.Common } } - internal int FillFromReader(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn parentChapterColumn, object parentChapterValue) + internal int FillFromReader(DataSet? dataset, DataTable? datatable, string? srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn? parentChapterColumn, object? parentChapterValue) { int rowsAddedToDataSet = 0; int schemaCount = 0; @@ -511,7 +513,7 @@ namespace System.Data.Common continue; // loop to next result } - SchemaMapping mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); + SchemaMapping? mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) if (null == mapping) @@ -640,20 +642,20 @@ namespace System.Data.Common return rowsAddedToDataSet; } - private SchemaMapping FillMappingInternal(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) + private SchemaMapping FillMappingInternal(DataSet? dataset, DataTable? datatable, string? srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn? parentChapterColumn, object? parentChapterValue) { bool withKeyInfo = (Data.MissingSchemaAction.AddWithKey == MissingSchemaAction); - string tmp = null; + string? tmp = null; if (null != dataset) { - tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount); + tmp = DataAdapter.GetSourceTableName(srcTable!, schemaCount); } return new SchemaMapping(this, dataset, datatable, dataReader, withKeyInfo, SchemaType.Mapped, tmp, true, parentChapterColumn, parentChapterValue); } - private SchemaMapping FillMapping(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) + private SchemaMapping? FillMapping(DataSet? dataset, DataTable? datatable, string? srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn? parentChapterColumn, object? parentChapterValue) { - SchemaMapping mapping = null; + SchemaMapping? mapping = null; if (_hasFillErrorHandler) { try @@ -702,7 +704,7 @@ namespace System.Data.Common [EditorBrowsable(EditorBrowsableState.Advanced)] public virtual IDataParameter[] GetFillParameters() => Array.Empty(); - internal DataTableMapping GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction) + internal DataTableMapping? GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction) { return DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMappings, sourceTableName, dataSetTableName, mappingAction); } @@ -718,10 +720,10 @@ namespace System.Data.Common protected virtual void OnFillError(FillErrorEventArgs value) { - ((FillErrorEventHandler)Events[s_eventFillError])?.Invoke(this, value); + ((FillErrorEventHandler?)Events[s_eventFillError])?.Invoke(this, value); } - private void OnFillErrorHandler(Exception e, DataTable dataTable, object[] dataValues) + private void OnFillErrorHandler(Exception e, DataTable? dataTable, object?[]? dataValues) { FillErrorEventArgs fillErrorEvent = new FillErrorEventArgs(dataTable, dataValues); fillErrorEvent.Errors = e; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs index bfbaf9d..7f53c99 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMapping.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; @@ -12,28 +13,29 @@ namespace System.Data.Common [TypeConverter(typeof(DataColumnMappingConverter))] public sealed class DataColumnMapping : MarshalByRefObject, IColumnMapping, ICloneable { - private DataColumnMappingCollection _parent; - private string _dataSetColumnName; - private string _sourceColumnName; + private DataColumnMappingCollection? _parent; + private string? _dataSetColumnName; + private string? _sourceColumnName; public DataColumnMapping() { } - public DataColumnMapping(string sourceColumn, string dataSetColumn) + public DataColumnMapping(string? sourceColumn, string? dataSetColumn) { SourceColumn = sourceColumn; DataSetColumn = dataSetColumn; } [DefaultValue("")] + [AllowNull] public string DataSetColumn { get { return _dataSetColumnName ?? string.Empty; } set { _dataSetColumnName = value; } } - internal DataColumnMappingCollection Parent + internal DataColumnMappingCollection? Parent { get { @@ -46,6 +48,7 @@ namespace System.Data.Common } [DefaultValue("")] + [AllowNull] public string SourceColumn { get { return _sourceColumnName ?? string.Empty; } @@ -68,13 +71,13 @@ namespace System.Data.Common } [EditorBrowsable(EditorBrowsableState.Advanced)] - public DataColumn GetDataColumnBySchemaAction(DataTable dataTable, Type dataType, MissingSchemaAction schemaAction) + public DataColumn? GetDataColumnBySchemaAction(DataTable dataTable, Type? dataType, MissingSchemaAction schemaAction) { return GetDataColumnBySchemaAction(SourceColumn, DataSetColumn, dataTable, dataType, schemaAction); } [EditorBrowsable(EditorBrowsableState.Advanced)] - public static DataColumn GetDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, DataTable dataTable, Type dataType, MissingSchemaAction schemaAction) + public static DataColumn? GetDataColumnBySchemaAction(string? sourceColumn, string? dataSetColumn, DataTable dataTable, Type? dataType, MissingSchemaAction schemaAction) { if (null == dataTable) { @@ -109,7 +112,7 @@ namespace System.Data.Common return CreateDataColumnBySchemaAction(sourceColumn, dataSetColumn, dataTable, dataType, schemaAction); } - internal static DataColumn CreateDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, DataTable dataTable, Type dataType, MissingSchemaAction schemaAction) + internal static DataColumn? CreateDataColumnBySchemaAction(string? sourceColumn, string? dataSetColumn, DataTable dataTable, Type? dataType, MissingSchemaAction schemaAction) { Debug.Assert(dataTable != null, "Should not call with a null DataTable"); if (string.IsNullOrEmpty(dataSetColumn)) @@ -121,7 +124,7 @@ namespace System.Data.Common { case MissingSchemaAction.Add: case MissingSchemaAction.AddWithKey: - return new DataColumn(dataSetColumn, dataType); + return new DataColumn(dataSetColumn, dataType!); case MissingSchemaAction.Ignore: return null; @@ -167,7 +170,7 @@ namespace System.Data.Common object[] values = new object[] { mapping.SourceColumn, mapping.DataSetColumn }; Type[] types = new Type[] { typeof(string), typeof(string) }; - ConstructorInfo ctor = typeof(DataColumnMapping).GetConstructor(types); + ConstructorInfo ctor = typeof(DataColumnMapping).GetConstructor(types)!; return new InstanceDescriptor(ctor, values); } return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs index bc68c21..7c6776d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs @@ -5,12 +5,13 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { public sealed class DataColumnMappingCollection : MarshalByRefObject, IColumnMappingCollection { - private List _items; // delay creation until AddWithoutEvents, Insert, CopyTo, GetEnumerator + private List? _items; // delay creation until AddWithoutEvents, Insert, CopyTo, GetEnumerator public DataColumnMappingCollection() { @@ -35,7 +36,7 @@ namespace System.Data.Common { get { return false; } } - object IList.this[int index] + object? IList.this[int index] { get { @@ -61,7 +62,7 @@ namespace System.Data.Common this[index] = (DataColumnMapping)value; } } - IColumnMapping IColumnMappingCollection.Add(string sourceColumnName, string dataSetColumnName) + IColumnMapping IColumnMappingCollection.Add(string? sourceColumnName, string? dataSetColumnName) { return Add(sourceColumnName, dataSetColumnName); } @@ -92,7 +93,7 @@ namespace System.Data.Common get { RangeCheck(index); - return _items[index]; + return _items![index]; } set { @@ -108,7 +109,7 @@ namespace System.Data.Common get { int index = RangeCheck(sourceColumn); - return _items[index]; + return _items![index]; } set { @@ -117,7 +118,7 @@ namespace System.Data.Common } } - public int Add(object value) + public int Add(object? value) { ValidateType(value); Add((DataColumnMapping)value); @@ -130,7 +131,7 @@ namespace System.Data.Common return value; } - public DataColumnMapping Add(string sourceColumn, string dataSetColumn) + public DataColumnMapping Add(string? sourceColumn, string? dataSetColumn) { return Add(new DataColumnMapping(sourceColumn, dataSetColumn)); } @@ -176,7 +177,7 @@ namespace System.Data.Common } } - private void AddWithoutEvents(DataColumnMapping value) + private void AddWithoutEvents([NotNull] DataColumnMapping? value) { Validate(-1, value); value.Parent = this; @@ -214,12 +215,12 @@ namespace System.Data.Common } } - public bool Contains(string value) + public bool Contains(string? value) { return (-1 != IndexOf(value)); } - public bool Contains(object value) + public bool Contains(object? value) { return (-1 != IndexOf(value)); } @@ -241,7 +242,7 @@ namespace System.Data.Common { throw ADP.ColumnsDataSetColumn(value); } - return _items[index]; + return _items![index]; } public IEnumerator GetEnumerator() @@ -249,14 +250,14 @@ namespace System.Data.Common return ArrayList().GetEnumerator(); } - public int IndexOf(object value) + public int IndexOf(object? value) { if (null != value) { ValidateType(value); for (int i = 0; i < Count; ++i) { - if (_items[i] == value) + if (_items![i] == value) { return i; } @@ -265,14 +266,14 @@ namespace System.Data.Common return -1; } - public int IndexOf(string sourceColumn) + public int IndexOf(string? sourceColumn) { if (!string.IsNullOrEmpty(sourceColumn)) { int count = Count; for (int i = 0; i < count; ++i) { - if (0 == ADP.SrcCompare(sourceColumn, _items[i].SourceColumn)) + if (0 == ADP.SrcCompare(sourceColumn, _items![i].SourceColumn)) { return i; } @@ -281,14 +282,14 @@ namespace System.Data.Common return -1; } - public int IndexOfDataSetColumn(string dataSetColumn) + public int IndexOfDataSetColumn(string? dataSetColumn) { if (!string.IsNullOrEmpty(dataSetColumn)) { int count = Count; for (int i = 0; i < count; ++i) { - if (0 == ADP.DstCompare(dataSetColumn, _items[i].DataSetColumn)) + if (0 == ADP.DstCompare(dataSetColumn, _items![i].DataSetColumn)) { return i; } @@ -297,7 +298,7 @@ namespace System.Data.Common return -1; } - public void Insert(int index, object value) + public void Insert(int index, object? value) { ValidateType(value); Insert(index, (DataColumnMapping)value); @@ -351,7 +352,7 @@ namespace System.Data.Common _items.RemoveAt(index); } - public void Remove(object value) + public void Remove(object? value) { ValidateType(value); Remove((DataColumnMapping)value); @@ -384,7 +385,7 @@ namespace System.Data.Common _items[index] = newValue; } - private void ValidateType(object value) + private void ValidateType([NotNull] object? value) { if (null == value) { @@ -396,7 +397,7 @@ namespace System.Data.Common } } - private void Validate(int index, DataColumnMapping value) + private void Validate(int index, [NotNull] DataColumnMapping? value) { if (null == value) { @@ -431,7 +432,7 @@ namespace System.Data.Common } } - internal void ValidateSourceColumn(int index, string value) + internal void ValidateSourceColumn(int index, string? value) { int pindex = IndexOf(value); if ((-1 != pindex) && (index != pindex)) @@ -441,14 +442,14 @@ namespace System.Data.Common } [EditorBrowsable(EditorBrowsableState.Advanced)] - public static DataColumn GetDataColumn(DataColumnMappingCollection columnMappings, string sourceColumn, Type dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) + public static DataColumn? GetDataColumn(DataColumnMappingCollection? columnMappings, string sourceColumn, Type? dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) { if (null != columnMappings) { int index = columnMappings.IndexOf(sourceColumn); if (-1 != index) { - return columnMappings._items[index].GetDataColumnBySchemaAction(dataTable, dataType, schemaAction); + return columnMappings._items![index].GetDataColumnBySchemaAction(dataTable, dataType, schemaAction); } } if (string.IsNullOrEmpty(sourceColumn)) @@ -470,14 +471,14 @@ namespace System.Data.Common } [EditorBrowsable(EditorBrowsableState.Advanced)] - public static DataColumnMapping GetColumnMappingBySchemaAction(DataColumnMappingCollection columnMappings, string sourceColumn, MissingMappingAction mappingAction) + public static DataColumnMapping? GetColumnMappingBySchemaAction(DataColumnMappingCollection? columnMappings, string sourceColumn, MissingMappingAction mappingAction) { if (null != columnMappings) { int index = columnMappings.IndexOf(sourceColumn); if (-1 != index) { - return columnMappings._items[index]; + return columnMappings._items![index]; } } if (string.IsNullOrEmpty(sourceColumn)) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs index a566bdf..7c09892 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs @@ -305,6 +305,8 @@ namespace System.Data.Common return new AttributeCollection(null); } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable string ICustomTypeDescriptor.GetClassName() { return null; @@ -335,6 +337,7 @@ namespace System.Data.Common { return null; } +#nullable enable EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs index d2a3d02..55cec5a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataStorage.cs @@ -62,7 +62,7 @@ namespace System.Data.Common { // for Whidbey 40426, searching down the Type[] is about 20% faster than using a Dictionary // must keep in same order as enum StorageType - private static readonly Type[] s_storageClassType = new Type[] { + private static readonly Type?[] s_storageClassType = new Type?[] { null, typeof(object), typeof(DBNull), @@ -113,9 +113,9 @@ namespace System.Data.Common internal readonly DataTable _table; internal readonly Type _dataType; internal readonly StorageType _storageTypeCode; - private System.Collections.BitArray _dbNullBits; + private System.Collections.BitArray _dbNullBits = default!; // Late-initialized - private readonly object _defaultValue; + private readonly object? _defaultValue; internal readonly object _nullValue; internal readonly bool _isCloneable; @@ -126,21 +126,21 @@ namespace System.Data.Common private static readonly Func> s_inspectTypeForInterfaces = InspectTypeForInterfaces; private static readonly ConcurrentDictionary> s_typeImplementsInterface = new ConcurrentDictionary>(); - protected DataStorage(DataColumn column, Type type, object defaultValue, StorageType storageType) + protected DataStorage(DataColumn column, Type type, object? defaultValue, StorageType storageType) : this(column, type, defaultValue, DBNull.Value, false, storageType) { } - protected DataStorage(DataColumn column, Type type, object defaultValue, object nullValue, StorageType storageType) + protected DataStorage(DataColumn column, Type type, object? defaultValue, object nullValue, StorageType storageType) : this(column, type, defaultValue, nullValue, false, storageType) { } - protected DataStorage(DataColumn column, Type type, object defaultValue, object nullValue, bool isICloneable, StorageType storageType) + protected DataStorage(DataColumn column, Type type, object? defaultValue, object nullValue, bool isICloneable, StorageType storageType) { Debug.Assert(storageType == GetStorageType(type), "Incorrect storage type specified"); _column = column; - _table = column.Table; + _table = column.Table!; _dataType = type; _storageTypeCode = storageType; _defaultValue = defaultValue; @@ -173,7 +173,8 @@ namespace System.Data.Common { return AggregateCount(recordNos); } - return null; + // Overridden implementation never return null, except for First which isn't actually implemented. + return null!; } public object AggregateCount(int[] recordNos) @@ -205,10 +206,10 @@ namespace System.Data.Common public abstract int Compare(int recordNo1, int recordNo2); // only does comparision, expect value to be of the correct type - public abstract int CompareValueTo(int recordNo1, object value); + public abstract int CompareValueTo(int recordNo1, object? value); // only does conversion with support for reference null - public virtual object ConvertValue(object value) + public virtual object? ConvertValue(object? value) { return value; } @@ -228,7 +229,8 @@ namespace System.Data.Common { return _nullValue; } - return _defaultValue; + // _defaultValue is null only for ObjectStorage, which does not call this method + return _defaultValue!; } public virtual int GetStringLength(int record) @@ -239,7 +241,7 @@ namespace System.Data.Common protected bool HasValue(int recordNo) { - return !_dbNullBits.Get(recordNo); + return !_dbNullBits!.Get(recordNo); } public virtual bool IsNull(int recordNo) @@ -274,7 +276,7 @@ namespace System.Data.Common } public abstract string ConvertObjectToXml(object value); - public virtual void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) + public virtual void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { xmlWriter.WriteString(ConvertObjectToXml(value)); // should it be NO OP? } @@ -298,7 +300,7 @@ namespace System.Data.Common { case StorageType.Empty: throw ExceptionBuilder.InvalidStorageType(TypeCode.Empty); case StorageType.DBNull: throw ExceptionBuilder.InvalidStorageType((TypeCode)2); // TypeCode.DBNull); - case StorageType.Object: return new ObjectStorage(column, dataType); + case StorageType.Object: return new ObjectStorage(column, dataType!); case StorageType.Boolean: return new BooleanStorage(column); case StorageType.Char: return new CharStorage(column); case StorageType.SByte: return new SByteStorage(column); @@ -315,14 +317,14 @@ namespace System.Data.Common case StorageType.DateTime: return new DateTimeStorage(column); case StorageType.TimeSpan: return new TimeSpanStorage(column); case StorageType.String: return new StringStorage(column); - case StorageType.Guid: return new ObjectStorage(column, dataType); + case StorageType.Guid: return new ObjectStorage(column, dataType!); - case StorageType.ByteArray: return new ObjectStorage(column, dataType); - case StorageType.CharArray: return new ObjectStorage(column, dataType); - case StorageType.Type: return new ObjectStorage(column, dataType); + case StorageType.ByteArray: return new ObjectStorage(column, dataType!); + case StorageType.CharArray: return new ObjectStorage(column, dataType!); + case StorageType.Type: return new ObjectStorage(column, dataType!); case StorageType.DateTimeOffset: return new DateTimeOffsetStorage(column); case StorageType.BigInteger: return new BigIntegerStorage(column); - case StorageType.Uri: return new ObjectStorage(column, dataType); + case StorageType.Uri: return new ObjectStorage(column, dataType!); case StorageType.SqlBinary: return new SqlBinaryStorage(column); case StorageType.SqlBoolean: return new SqlBooleanStorage(column); @@ -346,7 +348,7 @@ namespace System.Data.Common } } - internal static StorageType GetStorageType(Type dataType) + internal static StorageType GetStorageType(Type? dataType) { for (int i = 0; i < s_storageClassType.Length; ++i) { @@ -365,7 +367,8 @@ namespace System.Data.Common internal static Type GetTypeStorage(StorageType storageType) { - return s_storageClassType[(int)storageType]; + Debug.Assert(storageType != StorageType.Empty); + return s_storageClassType[(int)storageType]!; } internal static bool IsTypeCustomType(Type type) @@ -518,7 +521,7 @@ namespace System.Data.Common public static bool IsObjectSqlNull(object value) { - INullable inullable = (value as INullable); + INullable? inullable = (value as INullable); return ((null != inullable) && inullable.IsNull); } @@ -556,7 +559,7 @@ namespace System.Data.Common /// internal static Type GetType(string value) { - Type dataType = Type.GetType(value); // throwOnError=false, ignoreCase=fase + Type? dataType = Type.GetType(value); // throwOnError=false, ignoreCase=fase if (null == dataType) { if ("System.Numerics.BigInteger" == value) @@ -567,8 +570,8 @@ namespace System.Data.Common // prevent reading type from schema which implements IDynamicMetaObjectProvider and not IXmlSerializable // the check here prevents the type from being loaded in schema or as instance data (when DataType is object) - ObjectStorage.VerifyIDynamicMetaObjectProvider(dataType); - return dataType; + ObjectStorage.VerifyIDynamicMetaObjectProvider(dataType!); + return dataType!; } /// wrapper around Type.AssemblyQualifiedName @@ -579,7 +582,7 @@ namespace System.Data.Common { Debug.Assert(null != type, "null type"); ObjectStorage.VerifyIDynamicMetaObjectProvider(type); - return type.AssemblyQualifiedName; + return type.AssemblyQualifiedName!; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs index ca57fd9..cbf3743 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMapping.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; @@ -12,22 +13,22 @@ namespace System.Data.Common [TypeConverter(typeof(DataTableMappingConverter))] public sealed class DataTableMapping : MarshalByRefObject, ITableMapping, ICloneable { - private DataTableMappingCollection _parent; - private DataColumnMappingCollection _columnMappings; - private string _dataSetTableName; - private string _sourceTableName; + private DataTableMappingCollection? _parent; + private DataColumnMappingCollection? _columnMappings; + private string? _dataSetTableName; + private string? _sourceTableName; public DataTableMapping() { } - public DataTableMapping(string sourceTable, string dataSetTable) + public DataTableMapping(string? sourceTable, string? dataSetTable) { SourceTable = sourceTable; DataSetTable = dataSetTable; } - public DataTableMapping(string sourceTable, string dataSetTable, DataColumnMapping[] columnMappings) + public DataTableMapping(string? sourceTable, string? dataSetTable, DataColumnMapping[]? columnMappings) { SourceTable = sourceTable; DataSetTable = dataSetTable; @@ -48,7 +49,7 @@ namespace System.Data.Common { get { - DataColumnMappingCollection columnMappings = _columnMappings; + DataColumnMappingCollection? columnMappings = _columnMappings; if (null == columnMappings) { columnMappings = new DataColumnMappingCollection(); @@ -59,13 +60,14 @@ namespace System.Data.Common } [DefaultValue("")] + [AllowNull] public string DataSetTable { get { return _dataSetTableName ?? string.Empty; } set { _dataSetTableName = value; } } - internal DataTableMappingCollection Parent + internal DataTableMappingCollection? Parent { get { @@ -78,6 +80,7 @@ namespace System.Data.Common } [DefaultValue("")] + [AllowNull] public string SourceTable { get { return _sourceTableName ?? string.Empty; } @@ -109,19 +112,19 @@ namespace System.Data.Common } [EditorBrowsable(EditorBrowsableState.Advanced)] - public DataColumn GetDataColumn(string sourceColumn, Type dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) + public DataColumn? GetDataColumn(string sourceColumn, Type? dataType, DataTable dataTable, MissingMappingAction mappingAction, MissingSchemaAction schemaAction) { return DataColumnMappingCollection.GetDataColumn(_columnMappings, sourceColumn, dataType, dataTable, mappingAction, schemaAction); } [EditorBrowsable(EditorBrowsableState.Advanced)] - public DataColumnMapping GetColumnMappingBySchemaAction(string sourceColumn, MissingMappingAction mappingAction) + public DataColumnMapping? GetColumnMappingBySchemaAction(string sourceColumn, MissingMappingAction mappingAction) { return DataColumnMappingCollection.GetColumnMappingBySchemaAction(_columnMappings, sourceColumn, mappingAction); } [EditorBrowsable(EditorBrowsableState.Advanced)] - public DataTable GetDataTableBySchemaAction(DataSet dataSet, MissingSchemaAction schemaAction) + public DataTable? GetDataTableBySchemaAction(DataSet dataSet, MissingSchemaAction schemaAction) { if (null == dataSet) { @@ -191,7 +194,7 @@ namespace System.Data.Common object[] values = new object[] { mapping.SourceTable, mapping.DataSetTable, columnMappings }; Type[] types = new Type[] { typeof(string), typeof(string), typeof(DataColumnMapping[]) }; - ConstructorInfo ctor = typeof(DataTableMapping).GetConstructor(types); + ConstructorInfo ctor = typeof(DataTableMapping).GetConstructor(types)!; return new InstanceDescriptor(ctor, values); } return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs index 6859087..9cc1dcc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs @@ -5,13 +5,14 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { [ListBindable(false)] public sealed class DataTableMappingCollection : MarshalByRefObject, ITableMappingCollection { - private List _items; // delay creation until AddWithoutEvents, Insert, CopyTo, GetEnumerator + private List? _items; // delay creation until AddWithoutEvents, Insert, CopyTo, GetEnumerator public DataTableMappingCollection() { } @@ -22,7 +23,7 @@ namespace System.Data.Common // explicit IList implementation bool IList.IsReadOnly => false; bool IList.IsFixedSize => false; - object IList.this[int index] + object? IList.this[int index] { get { return this[index]; } set @@ -60,7 +61,7 @@ namespace System.Data.Common get { RangeCheck(index); - return _items[index]; + return _items![index]; } set { @@ -76,7 +77,7 @@ namespace System.Data.Common get { int index = RangeCheck(sourceTable); - return _items[index]; + return _items![index]; } set { @@ -85,7 +86,7 @@ namespace System.Data.Common } } - public int Add(object value) + public int Add(object? value) { ValidateType(value); Add((DataTableMapping)value); @@ -130,10 +131,10 @@ namespace System.Data.Common } } - public DataTableMapping Add(string sourceTable, string dataSetTable) => + public DataTableMapping Add(string? sourceTable, string? dataSetTable) => Add(new DataTableMapping(sourceTable, dataSetTable)); - private void AddWithoutEvents(DataTableMapping value) + private void AddWithoutEvents(DataTableMapping? value) { Validate(-1, value); value.Parent = this; @@ -164,9 +165,9 @@ namespace System.Data.Common } } - public bool Contains(string value) => (-1 != IndexOf(value)); + public bool Contains(string? value) => (-1 != IndexOf(value)); - public bool Contains(object value) => (-1 != IndexOf(value)); + public bool Contains(object? value) => (-1 != IndexOf(value)); public void CopyTo(Array array, int index) => ((ICollection)ArrayList()).CopyTo(array, index); @@ -179,19 +180,19 @@ namespace System.Data.Common { throw ADP.TablesDataSetTable(dataSetTable); } - return _items[index]; + return _items![index]; } public IEnumerator GetEnumerator() => ArrayList().GetEnumerator(); - public int IndexOf(object value) + public int IndexOf(object? value) { if (null != value) { ValidateType(value); for (int i = 0; i < Count; ++i) { - if (_items[i] == value) + if (_items![i] == value) { return i; } @@ -200,13 +201,13 @@ namespace System.Data.Common return -1; } - public int IndexOf(string sourceTable) + public int IndexOf(string? sourceTable) { if (!string.IsNullOrEmpty(sourceTable)) { for (int i = 0; i < Count; ++i) { - string value = _items[i].SourceTable; + string value = _items![i].SourceTable; if ((null != value) && (0 == ADP.SrcCompare(sourceTable, value))) { return i; @@ -216,13 +217,13 @@ namespace System.Data.Common return -1; } - public int IndexOfDataSetTable(string dataSetTable) + public int IndexOfDataSetTable(string? dataSetTable) { if (!string.IsNullOrEmpty(dataSetTable)) { for (int i = 0; i < Count; ++i) { - string value = _items[i].DataSetTable; + string value = _items![i].DataSetTable; if ((null != value) && (0 == ADP.DstCompare(dataSetTable, value))) { return i; @@ -232,7 +233,7 @@ namespace System.Data.Common return -1; } - public void Insert(int index, object value) + public void Insert(int index, object? value) { ValidateType(value); Insert(index, (DataTableMapping)value); @@ -286,7 +287,7 @@ namespace System.Data.Common _items.RemoveAt(index); } - public void Remove(object value) + public void Remove(object? value) { ValidateType(value); Remove((DataTableMapping)value); @@ -313,12 +314,12 @@ namespace System.Data.Common private void Replace(int index, DataTableMapping newValue) { Validate(index, newValue); - _items[index].Parent = null; + _items![index].Parent = null; newValue.Parent = this; _items[index] = newValue; } - private void ValidateType(object value) + private void ValidateType([NotNull] object? value) { if (null == value) { @@ -330,7 +331,7 @@ namespace System.Data.Common } } - private void Validate(int index, DataTableMapping value) + private void Validate(int index, [NotNull] DataTableMapping? value) { if (null == value) { @@ -364,7 +365,7 @@ namespace System.Data.Common } } - internal void ValidateSourceTable(int index, string value) + internal void ValidateSourceTable(int index, string? value) { int pindex = IndexOf(value); if ((-1 != pindex) && (index != pindex)) @@ -375,14 +376,14 @@ namespace System.Data.Common } [EditorBrowsable(EditorBrowsableState.Advanced)] - public static DataTableMapping GetTableMappingBySchemaAction(DataTableMappingCollection tableMappings, string sourceTable, string dataSetTable, MissingMappingAction mappingAction) + public static DataTableMapping? GetTableMappingBySchemaAction(DataTableMappingCollection? tableMappings, string sourceTable, string dataSetTable, MissingMappingAction mappingAction) { if (null != tableMappings) { int index = tableMappings.IndexOf(sourceTable); if (-1 != index) { - return tableMappings._items[index]; + return tableMappings._items![index]; } } if (string.IsNullOrEmpty(sourceTable)) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs index a9641a2..aca975e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeOffsetStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private static readonly DateTimeOffset s_defaultValue = DateTimeOffset.MinValue; - private DateTimeOffset[] _values; + private DateTimeOffset[] _values = default!; // Late-initialized internal DateTimeOffsetStorage(DataColumn column) : base(column, typeof(DateTimeOffset), s_defaultValue, StorageType.DateTimeOffset) @@ -58,12 +58,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: int count = 0; @@ -100,7 +100,7 @@ namespace System.Data.Common return DateTimeOffset.Compare(valueNo1, valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -118,7 +118,7 @@ namespace System.Data.Common return DateTimeOffset.Compare(valueNo1, (DateTimeOffset)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs index 43f7c17..30337ab 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DateTimeStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private static readonly DateTime s_defaultValue = DateTime.MinValue; - private DateTime[] _values; + private DateTime[] _values = default!; // Late-initialized internal DateTimeStorage(DataColumn column) : base(column, typeof(DateTime), s_defaultValue, StorageType.DateTime) @@ -58,12 +58,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: int count = 0; @@ -100,7 +100,7 @@ namespace System.Data.Common return DateTime.Compare(valueNo1, valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -118,7 +118,7 @@ namespace System.Data.Common return DateTime.Compare(valueNo1, (DateTime)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbColumn.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbColumn.cs index f4dfd63..289bf92 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbColumn.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public abstract class DbColumn diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbCommand.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbCommand.cs index 7a1a624..1f00276 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbCommand.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbCommand.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnection.cs index 7b99a8d..a749668 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnection.cs @@ -6,8 +6,6 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; -#nullable enable - namespace System.Data.Common { public abstract class DbConnection : Component, IDbConnection, IAsyncDisposable diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs index d643fa1..08e2c6e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs @@ -33,10 +33,10 @@ namespace System.Data.Common // synonyms hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string - public DbConnectionOptions(string connectionString, Dictionary synonyms, bool useOdbcRules) + public DbConnectionOptions(string? connectionString, Dictionary? synonyms, bool useOdbcRules) { _useOdbcRules = useOdbcRules; - _parsetable = new Dictionary(); + _parsetable = new Dictionary(); _usersConnectionString = ((null != connectionString) ? connectionString : ""); // first pass on parsing, initial syntax check @@ -48,11 +48,11 @@ namespace System.Data.Common } } - internal Dictionary Parsetable => _parsetable; + internal Dictionary Parsetable => _parsetable; - public string this[string keyword] => (string)_parsetable[keyword]; + public string? this[string keyword] => _parsetable[keyword]; - internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules) + internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string? keyValue, bool useOdbcRules) { ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); @@ -137,7 +137,7 @@ namespace System.Data.Common int copyPosition = 0; var builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair? current = _keyChain; null != current; current = current.Next) { if ((current.Name == keyword) && (current.Value == this[keyword])) { @@ -163,7 +163,7 @@ namespace System.Data.Common } [Conditional("DEBUG")] - static partial void DebugTraceKeyValuePair(string keyname, string keyvalue, Dictionary synonyms) + static partial void DebugTraceKeyValuePair(string keyname, string? keyvalue, Dictionary? synonyms) { Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower"); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs index bbb7f4a..533e6ed 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -159,7 +158,7 @@ namespace System.Data.Common Clear(); try { - for (NameValuePair pair = constr._keyChain; null != pair; pair = pair.Next) + for (NameValuePair? pair = constr._keyChain; null != pair; pair = pair.Next) { if (null != pair.Value) { @@ -503,7 +502,7 @@ namespace System.Data.Common } PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(keyword, - GetType(), vtype, false, useAttributes); + GetType(), vtype, false, useAttributes!); propertyDescriptors[keyword] = descriptor; } } @@ -562,6 +561,7 @@ namespace System.Data.Common return new PropertyDescriptorCollection(filteredPropertiesArray); } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated #nullable disable string ICustomTypeDescriptor.GetClassName() { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs index 7b6fdfe..16e792b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilderDescriptor.cs @@ -21,16 +21,16 @@ namespace System.Data.Common public override bool CanResetValue(object component) { - DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); + DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); return ((null != builder) && builder.ShouldSerialize(DisplayName)); } - public override object GetValue(object component) + public override object? GetValue(object component) { - DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); + DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); if (null != builder) { - object value; + object? value; if (builder.TryGetValue(DisplayName, out value)) { return value; @@ -41,7 +41,7 @@ namespace System.Data.Common public override void ResetValue(object component) { - DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); + DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); if (null != builder) { builder.Remove(DisplayName); @@ -53,9 +53,9 @@ namespace System.Data.Common } } - public override void SetValue(object component, object value) + public override void SetValue(object component, object? value) { - DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); + DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); if (null != builder) { // via the editor, empty string does a defacto Reset @@ -74,7 +74,7 @@ namespace System.Data.Common public override bool ShouldSerializeValue(object component) { - DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); + DbConnectionStringBuilder? builder = (component as DbConnectionStringBuilder); return ((null != builder) && builder.ShouldSerialize(DisplayName)); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs index 08f17fa..e86beec 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs @@ -5,6 +5,7 @@ using System.ComponentModel; using System.Collections.Generic; using System.Data.ProviderBase; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { @@ -15,7 +16,7 @@ namespace System.Data.Common internal static readonly object s_parameterValueNonNullValue = 0; internal static readonly object s_parameterValueNullValue = 1; - private IDbCommand _deleteCommand, _insertCommand, _selectCommand, _updateCommand; + private IDbCommand? _deleteCommand, _insertCommand, _selectCommand, _updateCommand; private CommandBehavior _fillCommandBehavior; @@ -27,7 +28,7 @@ namespace System.Data.Common internal StatementType _statementType; // the statement type of the command, needed for accept changes internal UpdateRowSource _updatedRowSource; // the UpdatedRowSource value from the command, to know whether we need to look for output parameters or not internal int? _recordsAffected; - internal Exception _errors; + internal Exception? _errors; } protected DbDataAdapter() : base() @@ -51,11 +52,11 @@ namespace System.Data.Common Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public DbCommand DeleteCommand + public DbCommand? DeleteCommand { get { - return (DbCommand)(_IDbDataAdapter.DeleteCommand); + return (DbCommand?)(_IDbDataAdapter.DeleteCommand); } set { @@ -63,7 +64,7 @@ namespace System.Data.Common } } - IDbCommand IDbDataAdapter.DeleteCommand + IDbCommand? IDbDataAdapter.DeleteCommand { get { @@ -91,11 +92,11 @@ namespace System.Data.Common Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public DbCommand InsertCommand + public DbCommand? InsertCommand { get { - return (DbCommand)(_IDbDataAdapter.InsertCommand); + return (DbCommand?)(_IDbDataAdapter.InsertCommand); } set { @@ -103,7 +104,7 @@ namespace System.Data.Common } } - IDbCommand IDbDataAdapter.InsertCommand + IDbCommand? IDbDataAdapter.InsertCommand { get { @@ -119,11 +120,11 @@ namespace System.Data.Common Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public DbCommand SelectCommand + public DbCommand? SelectCommand { get { - return (DbCommand)(_IDbDataAdapter.SelectCommand); + return (DbCommand?)(_IDbDataAdapter.SelectCommand); } set { @@ -131,7 +132,7 @@ namespace System.Data.Common } } - IDbCommand IDbDataAdapter.SelectCommand + IDbCommand? IDbDataAdapter.SelectCommand { get { @@ -163,11 +164,11 @@ namespace System.Data.Common Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] - public DbCommand UpdateCommand + public DbCommand? UpdateCommand { get { - return (DbCommand)(_IDbDataAdapter.UpdateCommand); + return (DbCommand?)(_IDbDataAdapter.UpdateCommand); } set { @@ -175,7 +176,7 @@ namespace System.Data.Common } } - IDbCommand IDbDataAdapter.UpdateCommand + IDbCommand? IDbDataAdapter.UpdateCommand { get { @@ -248,9 +249,9 @@ namespace System.Data.Common _IDbDataAdapter.DeleteCommand = CloneCommand(pfrom.DeleteCommand); } - private IDbCommand CloneCommand(IDbCommand command) + private IDbCommand? CloneCommand(IDbCommand? command) { - return (IDbCommand)((command is ICloneable) ? ((ICloneable)command).Clone() : null); + return (IDbCommand?)((command is ICloneable) ? ((ICloneable)command).Clone() : null); } protected virtual RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) @@ -287,14 +288,14 @@ namespace System.Data.Common throw ADP.NotSupported(); } - public DataTable FillSchema(DataTable dataTable, SchemaType schemaType) + public DataTable? FillSchema(DataTable dataTable, SchemaType schemaType) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTable, schemaType={1}", ObjectID, schemaType); try { - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return FillSchema(dataTable, schemaType, selectCmd, cmdBehavior); + return FillSchema(dataTable, schemaType, selectCmd!, cmdBehavior); } finally { @@ -307,13 +308,13 @@ namespace System.Data.Common long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, schemaType={1}", ObjectID, schemaType); try { - IDbCommand command = _IDbDataAdapter.SelectCommand; + IDbCommand? command = _IDbDataAdapter.SelectCommand; if (DesignMode && ((null == command) || (null == command.Connection) || string.IsNullOrEmpty(command.CommandText))) { return Array.Empty(); // design-time support } CommandBehavior cmdBehavior = FillCommandBehavior; - return FillSchema(dataSet, schemaType, command, DbDataAdapter.DefaultSourceTableName, cmdBehavior); + return FillSchema(dataSet, schemaType, command!, DbDataAdapter.DefaultSourceTableName, cmdBehavior); } finally { @@ -326,9 +327,9 @@ namespace System.Data.Common long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet, schemaType={1}, srcTable={2}", ObjectID, (int)schemaType, srcTable); try { - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return FillSchema(dataSet, schemaType, selectCmd, srcTable, cmdBehavior); + return FillSchema(dataSet, schemaType, selectCmd!, srcTable, cmdBehavior); } finally { @@ -357,7 +358,8 @@ namespace System.Data.Common { throw ADP.MissingSelectCommand(ADP.FillSchema); } - return (DataTable[])FillSchemaInternal(dataSet, null, schemaType, command, srcTable, behavior); + // Never returns null if dataSet is non-null + return (DataTable[])FillSchemaInternal(dataSet, null, schemaType, command, srcTable, behavior)!; } finally { @@ -365,7 +367,7 @@ namespace System.Data.Common } } - protected virtual DataTable FillSchema(DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior) + protected virtual DataTable? FillSchema(DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataTable, schemaType, command, behavior={1}", ObjectID, behavior); try @@ -388,7 +390,7 @@ namespace System.Data.Common { srcTableName = TableMappings[index].SourceTable; } - return (DataTable)FillSchemaInternal(null, dataTable, schemaType, command, srcTableName, behavior | CommandBehavior.SingleResult); + return (DataTable?)FillSchemaInternal(null, dataTable, schemaType, command, srcTableName, behavior | CommandBehavior.SingleResult); } finally { @@ -396,9 +398,9 @@ namespace System.Data.Common } } - private object FillSchemaInternal(DataSet dataset, DataTable datatable, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior) + private object? FillSchemaInternal(DataSet? dataset, DataTable? datatable, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior) { - object dataTables = null; + object? dataTables = null; bool restoreNullConnection = (null == command.Connection); try { @@ -416,7 +418,7 @@ namespace System.Data.Common } else { - dataTables = FillSchema(dataset, schemaType, srcTable, dataReader); + dataTables = FillSchema(dataset!, schemaType, srcTable, dataReader); } } } @@ -442,9 +444,9 @@ namespace System.Data.Common try { // delegate to Fill4 - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return Fill(dataSet, 0, 0, DbDataAdapter.DefaultSourceTableName, selectCmd, cmdBehavior); + return Fill(dataSet, 0, 0, DbDataAdapter.DefaultSourceTableName, selectCmd!, cmdBehavior); } finally { @@ -458,9 +460,9 @@ namespace System.Data.Common try { // delegate to Fill4 - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return Fill(dataSet, 0, 0, srcTable, selectCmd, cmdBehavior); + return Fill(dataSet, 0, 0, srcTable, selectCmd!, cmdBehavior); } finally { @@ -474,9 +476,9 @@ namespace System.Data.Common try { // delegate to Fill4 - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return Fill(dataSet, startRecord, maxRecords, srcTable, selectCmd, cmdBehavior); + return Fill(dataSet, startRecord, maxRecords, srcTable, selectCmd!, cmdBehavior); } finally { @@ -524,9 +526,9 @@ namespace System.Data.Common { // delegate to Fill8 DataTable[] dataTables = new DataTable[1] { dataTable }; - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return Fill(dataTables, 0, 0, selectCmd, cmdBehavior); + return Fill(dataTables, 0, 0, selectCmd!, cmdBehavior); } finally { @@ -540,9 +542,9 @@ namespace System.Data.Common try { // delegate to Fill8 - IDbCommand selectCmd = _IDbDataAdapter.SelectCommand; + IDbCommand? selectCmd = _IDbDataAdapter.SelectCommand; CommandBehavior cmdBehavior = FillCommandBehavior; - return Fill(dataTables, startRecord, maxRecords, selectCmd, cmdBehavior); + return Fill(dataTables, startRecord, maxRecords, selectCmd!, cmdBehavior); } finally { @@ -602,7 +604,7 @@ namespace System.Data.Common } } - private int FillInternal(DataSet dataset, DataTable[] datatables, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior) + private int FillInternal(DataSet? dataset, DataTable[]? datatables, int startRecord, int maxRecords, string? srcTable, IDbCommand command, CommandBehavior behavior) { int rowsAddedToDataSet = 0; bool restoreNullConnection = (null == command.Connection); @@ -623,7 +625,7 @@ namespace System.Data.Common QuietOpen(activeConnection, out originalState); behavior |= CommandBehavior.SequentialAccess; - IDataReader dataReader = null; + IDataReader? dataReader = null; try { dataReader = command.ExecuteReader(behavior); @@ -634,7 +636,7 @@ namespace System.Data.Common } else { - rowsAddedToDataSet = Fill(dataset, srcTable, dataReader, startRecord, maxRecords); + rowsAddedToDataSet = Fill(dataset!, srcTable!, dataReader, startRecord, maxRecords); } } finally @@ -670,7 +672,7 @@ namespace System.Data.Common throw ADP.NotSupported(); } - protected virtual bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out Exception error) + protected virtual bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out Exception? error) { // Called to retrieve the records affected from a specific batched command, // first argument is the value that was returned by AddToBatch when it @@ -688,8 +690,8 @@ namespace System.Data.Common [EditorBrowsable(EditorBrowsableState.Advanced)] public override IDataParameter[] GetFillParameters() { - IDataParameter[] value = null; - IDbCommand select = _IDbDataAdapter.SelectCommand; + IDataParameter[]? value = null; + IDbCommand? select = _IDbDataAdapter.SelectCommand; if (null != select) { IDataParameterCollection parameters = select.Parameters; @@ -708,7 +710,7 @@ namespace System.Data.Common internal DataTableMapping GetTableMapping(DataTable dataTable) { - DataTableMapping tableMapping = null; + DataTableMapping? tableMapping = null; int index = IndexOfDataSetTable(dataTable.TableName); if (-1 != index) { @@ -753,7 +755,7 @@ namespace System.Data.Common string columnName = parameter.SourceColumn; if (!string.IsNullOrEmpty(columnName)) { - DataColumn dataColumn = mappings.GetDataColumn(columnName, null, row.Table, missingMapping, missingSchema); + DataColumn? dataColumn = mappings.GetDataColumn(columnName, null, row.Table, missingMapping, missingSchema); if (null != dataColumn) { DataRowVersion version = DbDataAdapter.GetParameterSourceVersion(typeIndex, parameter); @@ -764,7 +766,7 @@ namespace System.Data.Common parameter.Value = null; } - DbParameter dbparameter = (parameter as DbParameter); + DbParameter? dbparameter = (parameter as DbParameter); if ((null != dbparameter) && dbparameter.SourceColumnNullMapping) { Debug.Assert(DbType.Int32 == parameter.DbType, "unexpected DbType"); @@ -779,14 +781,14 @@ namespace System.Data.Common { if (0 != (ParameterDirection.Output & parameter.Direction)) { - object value = parameter.Value; + object? value = parameter.Value; if (null != value) { // null means default, meaning we leave the current DataRow value alone string columnName = parameter.SourceColumn; if (!string.IsNullOrEmpty(columnName)) { - DataColumn dataColumn = mappings.GetDataColumn(columnName, null, row.Table, missingMapping, missingSchema); + DataColumn? dataColumn = mappings.GetDataColumn(columnName, null, row.Table, missingMapping, missingSchema); if (null != dataColumn) { if (dataColumn.ReadOnly) @@ -850,7 +852,7 @@ namespace System.Data.Common } else if (0 != dataRows.Length) { - DataTable dataTable = null; + DataTable? dataTable = null; for (int i = 0; i < dataRows.Length; ++i) { if ((null != dataRows[i]) && (dataTable != dataRows[i].Table)) @@ -886,7 +888,7 @@ namespace System.Data.Common throw ADP.UpdateRequiresDataTable(nameof(dataTable)); } - DataTableMapping tableMapping = null; + DataTableMapping? tableMapping = null; int index = IndexOfDataSetTable(dataTable.TableName); if (-1 != index) { @@ -924,13 +926,13 @@ namespace System.Data.Common int rowsAffected = 0; - DataTableMapping tableMapping = GetTableMappingBySchemaAction(srcTable, srcTable, UpdateMappingAction); + DataTableMapping? tableMapping = GetTableMappingBySchemaAction(srcTable, srcTable, UpdateMappingAction); Debug.Assert(null != tableMapping, "null TableMapping when MissingMappingAction.Error"); // the ad-hoc scenario of no dataTable just returns // ad-hoc scenario is defined as MissingSchemaAction.Add or MissingSchemaAction.Ignore System.Data.MissingSchemaAction schemaAction = UpdateSchemaAction; - DataTable dataTable = tableMapping.GetDataTableBySchemaAction(dataSet, schemaAction); + DataTable? dataTable = tableMapping.GetDataTableBySchemaAction(dataSet, schemaAction); if (null != dataTable) { rowsAffected = UpdateFromDataTable(dataTable, tableMapping); @@ -959,17 +961,17 @@ namespace System.Data.Common // If records were affected, increment row count by one - that is number of rows affected in dataset. int cumulativeDataRowsAffected = 0; - IDbConnection[] connections = new IDbConnection[5]; // one for each statementtype + IDbConnection?[] connections = new IDbConnection[5]; // one for each statementtype ConnectionState[] connectionStates = new ConnectionState[5]; // closed by default (== 0) bool useSelectConnectionState = false; - IDbCommand tmpcmd = _IDbDataAdapter.SelectCommand; + IDbCommand? tmpcmd = _IDbDataAdapter.SelectCommand; if (null != tmpcmd) { connections[0] = tmpcmd.Connection; if (null != connections[0]) { - connectionStates[0] = connections[0].State; + connectionStates[0] = connections[0]!.State; useSelectConnectionState = true; } } @@ -995,7 +997,7 @@ namespace System.Data.Common InitializeBatching(); } StatementType statementType = StatementType.Select; - IDbCommand dataCommand = null; + IDbCommand? dataCommand = null; // for each row which is either insert, update, or delete foreach (DataRow dataRow in dataRows) @@ -1030,7 +1032,10 @@ namespace System.Data.Common } // setup the event to be raised - RowUpdatingEventArgs rowUpdatingEvent = CreateRowUpdatingEvent(dataRow, dataCommand, statementType, tableMapping); + // TODO: the event may be raised with a null command, but only if the update, but only if + // the update attempt fails (because no command was configured). We should not emit the + // event in this case. + RowUpdatingEventArgs? rowUpdatingEvent = CreateRowUpdatingEvent(dataRow, dataCommand!, statementType, tableMapping); // this try/catch for any exceptions during the parameter initialization try @@ -1051,7 +1056,7 @@ namespace System.Data.Common OnRowUpdating(rowUpdatingEvent); // user may throw out of Update without completing batch - IDbCommand tmpCommand = rowUpdatingEvent.Command; + IDbCommand? tmpCommand = rowUpdatingEvent.Command; isCommandFromRowUpdating = (dataCommand != tmpCommand); dataCommand = tmpCommand; tmpCommand = null; @@ -1089,7 +1094,7 @@ namespace System.Data.Common // else onward to Append/ExecuteNonQuery/ExecuteReader rowUpdatingEvent = null; - RowUpdatedEventArgs rowUpdatedEvent = null; + RowUpdatedEventArgs? rowUpdatedEvent = null; if (1 == maxBatchCommands) { @@ -1106,7 +1111,7 @@ namespace System.Data.Common } else { - Exception errors = null; + Exception? errors = null; try { @@ -1153,7 +1158,8 @@ namespace System.Data.Common if (null != errors) { - rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand, StatementType.Batch, tableMapping); + // TODO: See above comment on dataCommand being null + rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand!, StatementType.Batch, tableMapping); rowUpdatedEvent.Errors = errors; rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; @@ -1175,7 +1181,8 @@ namespace System.Data.Common } } - rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand, statementType, tableMapping); + // TODO: See above comment on dataCommand being null + rowUpdatedEvent = CreateRowUpdatedEvent(dataRow, dataCommand!, statementType, tableMapping); // this try/catch for any exceptions during the execution, population, output parameters try @@ -1233,7 +1240,7 @@ namespace System.Data.Common bool clearBatchOnSkipAll = (UpdateStatus.ErrorsOccurred == rowUpdatedEvent.Status); { - Exception errors = rowUpdatedEvent.Errors; + Exception? errors = rowUpdatedEvent.Errors; OnRowUpdated(rowUpdatedEvent); // user may throw out of Update // NOTE: the contents of rowBatch are now tainted... if (errors != rowUpdatedEvent.Errors) @@ -1272,7 +1279,9 @@ namespace System.Data.Common // must handle the last batch if (1 != maxBatchCommands && 0 < commandCount) { - RowUpdatedEventArgs rowUpdatedEvent = CreateRowUpdatedEvent(null, dataCommand, statementType, tableMapping); + // TODO: See above comment on dataCommand being null + // TODO: DataRow is null because we call AdapterInit below, which populars rows + RowUpdatedEventArgs rowUpdatedEvent = CreateRowUpdatedEvent(null!, dataCommand!, statementType, tableMapping); try { @@ -1307,7 +1316,7 @@ namespace System.Data.Common rowUpdatedEvent.Errors = e; rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; } - Exception errors = rowUpdatedEvent.Errors; + Exception? errors = rowUpdatedEvent.Errors; OnRowUpdated(rowUpdatedEvent); // user may throw out of Update // NOTE: the contents of rowBatch are now tainted... if (errors != rowUpdatedEvent.Errors) @@ -1346,6 +1355,7 @@ namespace System.Data.Common private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCount, RowUpdatedEventArgs rowUpdatedEvent) { + Debug.Assert(rowUpdatedEvent.Rows != null); try { // the batch execution may succeed, partially succeed and throw an exception (or not), or totally fail @@ -1364,7 +1374,7 @@ namespace System.Data.Common int checkRecordsAffected = 0; bool hasConcurrencyViolation = false; - List rows = null; + List? rows = null; // walk through the batch to build the sum of recordsAffected // determine possible indivdual messages per datarow @@ -1431,7 +1441,7 @@ namespace System.Data.Common { // bug50526, an exception if no records affected and attempted an Update/Delete Debug.Assert(null == rowUpdatedEvent.Errors, "Continue - but contains an exception"); - DataRow[] rowsInError = (null != rows) ? rows.ToArray() : rowUpdatedEvent.Rows; + DataRow[] rowsInError = (null != rows) ? rows.ToArray() : rowUpdatedEvent.Rows!; rowUpdatedEvent.Errors = ADP.UpdateConcurrencyViolation(StatementType.Batch, commandCount - rowsInError.Length, commandCount, rowsInError); rowUpdatedEvent.Status = UpdateStatus.ErrorsOccurred; } @@ -1439,10 +1449,9 @@ namespace System.Data.Common } } - private ConnectionState UpdateConnectionOpen(IDbConnection connection, StatementType statementType, IDbConnection[] connections, ConnectionState[] connectionStates, bool useSelectConnectionState) + private ConnectionState UpdateConnectionOpen(IDbConnection connection, StatementType statementType, IDbConnection?[] connections, ConnectionState[] connectionStates, bool useSelectConnectionState) { Debug.Assert(null != connection, "unexpected null connection"); - Debug.Assert(null != connection, "unexpected null connection"); int index = (int)statementType; if (connection != connections[index]) { @@ -1456,7 +1465,7 @@ namespace System.Data.Common QuietOpen(connection, out connectionStates[index]); if (useSelectConnectionState && (connections[0] == connection)) { - connectionStates[index] = connections[0].State; + connectionStates[index] = connections[0]!.State; } } return connection.State; @@ -1612,8 +1621,9 @@ namespace System.Data.Common bool acdu = AcceptChangesDuringUpdate; for (int i = 0; i < commandCount; i++) { - DataRow row = batchCommands[i]._row; - if ((null == batchCommands[i]._errors) && batchCommands[i]._recordsAffected.HasValue && (0 != batchCommands[i]._recordsAffected.Value)) + var batchCommand = batchCommands[i]; + DataRow row = batchCommand._row; + if ((null == batchCommand._errors) && batchCommand._recordsAffected != null && (0 != batchCommand._recordsAffected.Value)) { Debug.Assert(null != row, "null dataRow?"); if (acdu) @@ -1632,7 +1642,7 @@ namespace System.Data.Common private int UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, int commandCount) { Debug.Assert(null != batchCommands, "null batchCommands?"); - Exception errors = rowUpdatedEvent.Errors; + Exception? errors = rowUpdatedEvent.Errors; if (null == errors) { // user changed status to ErrorsOccurred without supplying an exception message @@ -1649,9 +1659,9 @@ namespace System.Data.Common DataRow row = batchCommands[i]._row; Debug.Assert(null != row, "null dataRow?"); - if (null != batchCommands[i]._errors) + if (batchCommands[i]._errors is { } commandErrors) { // will exist if 0 == RecordsAffected - string rowMsg = batchCommands[i]._errors.Message; + string rowMsg = commandErrors.Message; if (string.IsNullOrEmpty(rowMsg)) { rowMsg = message; @@ -1702,7 +1712,7 @@ namespace System.Data.Common private void UpdatingRowStatusErrors(RowUpdatingEventArgs rowUpdatedEvent, DataRow dataRow) { Debug.Assert(null != dataRow, "null dataRow"); - Exception errors = rowUpdatedEvent.Errors; + Exception? errors = rowUpdatedEvent.Errors; if (null == errors) { @@ -1721,7 +1731,7 @@ namespace System.Data.Common private static IDbConnection GetConnection1(DbDataAdapter adapter) { - IDbCommand command = adapter._IDbDataAdapter.SelectCommand; + IDbCommand? command = adapter._IDbDataAdapter.SelectCommand; if (null == command) { command = adapter._IDbDataAdapter.InsertCommand; @@ -1734,7 +1744,7 @@ namespace System.Data.Common } } } - IDbConnection connection = null; + IDbConnection? connection = null; if (null != command) { connection = command.Connection; @@ -1750,7 +1760,7 @@ namespace System.Data.Common { Debug.Assert(null != command, "GetConnection3: null command"); Debug.Assert(!string.IsNullOrEmpty(method), "missing method name"); - IDbConnection connection = command.Connection; + IDbConnection? connection = command.Connection; if (null == connection) { throw ADP.ConnectionRequired_Res(method); @@ -1761,7 +1771,7 @@ namespace System.Data.Common private static IDbConnection GetConnection4(DbDataAdapter adapter, IDbCommand command, StatementType statementType, bool isCommandFromRowUpdating) { Debug.Assert(null != command, "GetConnection4: null command"); - IDbConnection connection = command.Connection; + IDbConnection? connection = command.Connection; if (null == connection) { throw ADP.UpdateConnectionRequired(statementType, isCommandFromRowUpdating); @@ -1783,7 +1793,7 @@ namespace System.Data.Common } } - private static void QuietClose(IDbConnection connection, ConnectionState originalState) + private static void QuietClose(IDbConnection? connection, ConnectionState originalState) { // close the connection if: // * it was closed on first use and adapter has opened it, AND diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs index 4753058..6e405dc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs index 98ce75c..97e0faf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataRecord.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataRecord.cs index 0187560..189e176 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataRecord.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataRecord.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; namespace System.Data.Common @@ -69,6 +68,7 @@ namespace System.Data.Common // ICustomTypeDescriptor // +// TODO: Enable after System.ComponentModel.TypeConverter is annotated #nullable disable AttributeCollection ICustomTypeDescriptor.GetAttributes() => new AttributeCollection(null); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataSourceEnumerator.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataSourceEnumerator.cs index bfe9f27..dca5950 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataSourceEnumerator.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataSourceEnumerator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public abstract class DbDataSourceEnumerator diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs index 3dea7db..35a5ae9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs @@ -11,10 +11,10 @@ namespace System.Data.Common public class DbEnumerator : IEnumerator { internal IDataReader _reader; - internal DbDataRecord _current; - internal SchemaInfo[] _schemaInfo; // shared schema info among all the data records - internal PropertyDescriptorCollection _descriptors; // cached property descriptors - private FieldNameLookup _fieldNameLookup; + internal DbDataRecord? _current; + internal SchemaInfo[]? _schemaInfo; // shared schema info among all the data records + internal PropertyDescriptorCollection? _descriptors; // cached property descriptors + private FieldNameLookup? _fieldNameLookup; private readonly bool _closeReader; // users must get enumerators off of the datareader interfaces @@ -47,7 +47,8 @@ namespace System.Data.Common { } - public object Current => _current; + // TODO: this should throw InvalidOperationException if null + public object Current => _current!; public bool MoveNext() { @@ -64,7 +65,7 @@ namespace System.Data.Common // setup our current record object[] values = new object[_schemaInfo.Length]; _reader.GetValues(values); // this.GetValues() - _current = new DataRecordInternal(_schemaInfo, values, _descriptors, _fieldNameLookup); + _current = new DataRecordInternal(_schemaInfo, values, _descriptors, _fieldNameLookup!); return true; } if (_closeReader) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbException.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbException.cs index 7021d06..25bebd9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { [Serializable] diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataCollectionNames.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataCollectionNames.cs index 2c3f5f7..d6aa453 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataCollectionNames.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataCollectionNames.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public static class DbMetaDataCollectionNames diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataColumnNames.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataColumnNames.cs index d13a796..61a3ec4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataColumnNames.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbMetaDataColumnNames.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public static class DbMetaDataColumnNames diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbParameter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbParameter.cs index 47df5f1..c637e4f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbParameter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbParameter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbParameterCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbParameterCollection.cs index 64ec74e..e826480 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbParameterCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbParameterCollection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; using System.Collections; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs index 8731859..2ad35f7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactories.cs @@ -11,8 +11,6 @@ using System.Linq; using System.Reflection; using System.Threading; -#nullable enable - namespace System.Data.Common { public static partial class DbProviderFactories @@ -57,7 +55,7 @@ namespace System.Data.Common { ADP.CheckArgumentNull(providerRow, nameof(providerRow)); - DataColumn assemblyQualifiedNameColumn = providerRow.Table.Columns[AssemblyQualifiedNameColumnName]; + DataColumn? assemblyQualifiedNameColumn = providerRow.Table.Columns[AssemblyQualifiedNameColumnName]; if (null == assemblyQualifiedNameColumn) { throw ADP.Argument(SR.ADP_DbProviderFactories_NoAssemblyQualifiedName); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.CreatePermission.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.CreatePermission.cs index 013c4a6..2591e36 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.CreatePermission.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.CreatePermission.cs @@ -1,5 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. + using System.Security; using System.Security.Permissions; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs index 69cbb52..70ad0e9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public abstract partial class DbProviderFactory diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderSpecificTypePropertyAttribute.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderSpecificTypePropertyAttribute.cs index de4adce..38b196c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderSpecificTypePropertyAttribute.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbProviderSpecificTypePropertyAttribute.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbTransaction.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbTransaction.cs index df53e69..fe357a6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbTransaction.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbTransaction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading; using System.Threading.Tasks; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs index 3a58a53..a102ae4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DecimalStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const decimal DefaultValue = decimal.Zero; - private decimal[] _values; + private decimal[] _values = default!; // Late-initialized internal DecimalStorage(DataColumn column) : base(column, typeof(decimal), DefaultValue, StorageType.Decimal) @@ -134,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -166,7 +166,7 @@ namespace System.Data.Common return decimal.Compare(valueNo1, valueNo2); // InternalCall } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -184,7 +184,7 @@ namespace System.Data.Common return decimal.Compare(valueNo1, (decimal)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs index 28fe89b..e27658b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DoubleStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const double defaultValue = 0.0d; - private double[] _values; + private double[] _values = default!; // Late-initialized internal DoubleStorage(DataColumn column) : base(column, typeof(double), defaultValue, StorageType.Double) @@ -129,12 +129,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -161,7 +161,7 @@ namespace System.Data.Common return valueNo1.CompareTo(valueNo2); // not simple, checks Nan } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -183,7 +183,7 @@ namespace System.Data.Common return valueNo1.CompareTo((double)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs b/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs index 2140f8b..ddca3b7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/FieldNameLookup.cs @@ -6,20 +6,19 @@ using System.Data.Common; using System.Diagnostics; using System.Globalization; - namespace System.Data.ProviderBase { internal sealed class FieldNameLookup { // hashtable stores the index into the _fieldNames, match via case-sensitive - private Hashtable _fieldNameLookup; + private Hashtable? _fieldNameLookup; // original names for linear searches when exact matches fail private readonly string[] _fieldNames; // if _defaultLocaleID is -1 then _compareInfo is initialized with InvariantCulture CompareInfo // otherwise it is specified by the server? for the correct compare info - private CompareInfo _compareInfo; + private CompareInfo? _compareInfo; private readonly int _defaultLocaleID; public FieldNameLookup(IDataRecord reader, int defaultLocaleID) @@ -56,7 +55,7 @@ namespace System.Data.ProviderBase GenerateLookup(); } int index; - object value = _fieldNameLookup[fieldName]; + object? value = _fieldNameLookup![fieldName]; if (null != value) { // via case sensitive search, first match with lowest ordinal matches @@ -77,7 +76,7 @@ namespace System.Data.ProviderBase private int LinearIndexOf(string fieldName, CompareOptions compareOptions) { - CompareInfo compareInfo = _compareInfo; + CompareInfo? compareInfo = _compareInfo; if (null == compareInfo) { if (-1 != _defaultLocaleID) @@ -95,7 +94,7 @@ namespace System.Data.ProviderBase { if (0 == compareInfo.Compare(fieldName, _fieldNames[i], compareOptions)) { - _fieldNameLookup[fieldName] = i; // add an exact match for the future + _fieldNameLookup![fieldName] = i; // add an exact match for the future return i; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/IDbColumnSchemaGenerator.cs b/src/libraries/System.Data.Common/src/System/Data/Common/IDbColumnSchemaGenerator.cs index 0ec217b..6bb0c8c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/IDbColumnSchemaGenerator.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/IDbColumnSchemaGenerator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public interface IDbColumnSchemaGenerator diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs index 011ca53..ba44cf1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/Int16Storage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const short defaultValue = 0; - private short[] _values; + private short[] _values = default!; // Late-initialized internal Int16Storage(DataColumn column) : base(column, typeof(short), defaultValue, StorageType.Int16) @@ -135,12 +135,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -178,7 +178,7 @@ namespace System.Data.Common return (valueNo1 - valueNo2); // copied from Int16.CompareTo(Int16) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -197,7 +197,7 @@ namespace System.Data.Common //return(valueNo1 - valueNo2); // copied from Int16.CompareTo(Int16) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs index d0c9a44..015d46b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/Int32Storage.cs @@ -4,14 +4,13 @@ using System.Xml; using System.Collections; - namespace System.Data.Common { internal sealed class Int32Storage : DataStorage { private const int defaultValue = 0; // Convert.ToInt32(null) - private int[] _values; + private int[] _values = default!; // Late-initialized internal Int32Storage(DataColumn column) : base(column, typeof(int), defaultValue, StorageType.Int32) @@ -135,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -178,7 +177,7 @@ namespace System.Data.Common return (valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to Int32.CompareTo(Int32) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -197,7 +196,7 @@ namespace System.Data.Common //return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to Int32.CompareTo(Int32) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs index c3a4eb7..2a6dbc0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/Int64Storage.cs @@ -4,14 +4,13 @@ using System.Xml; using System.Collections; - namespace System.Data.Common { internal sealed class Int64Storage : DataStorage { private const long defaultValue = 0; - private long[] _values; + private long[] _values = default!; // Late-initialized internal Int64Storage(DataColumn column) : base(column, typeof(long), defaultValue, StorageType.Int64) @@ -135,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -170,7 +169,7 @@ namespace System.Data.Common return (valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to Int64.CompareTo(Int64) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -189,7 +188,7 @@ namespace System.Data.Common //return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to Int64.CompareTo(Int64) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs index 5a85eb9..f220cf8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs @@ -16,7 +16,7 @@ namespace System.Data.Common { private enum Families { DATETIME, NUMBER, STRING, BOOLEAN, ARRAY }; - private object[] _values; + private object?[] _values = default!; // Late-initialized private readonly bool _implementsIXmlSerializable; internal ObjectStorage(DataColumn column, Type type) @@ -32,8 +32,8 @@ namespace System.Data.Common public override int Compare(int recordNo1, int recordNo2) { - object valueNo1 = _values[recordNo1]; - object valueNo2 = _values[recordNo2]; + object? valueNo1 = _values[recordNo1]; + object? valueNo2 = _values[recordNo2]; if (valueNo1 == valueNo2) return 0; @@ -42,7 +42,7 @@ namespace System.Data.Common if (valueNo2 == null) return 1; - IComparable icomparable = (valueNo1 as IComparable); + IComparable? icomparable = (valueNo1 as IComparable); if (null != icomparable) { try @@ -57,13 +57,13 @@ namespace System.Data.Common return CompareWithFamilies(valueNo1, valueNo2); } - public override int CompareValueTo(int recordNo1, object value) + public override int CompareValueTo(int recordNo1, object? value) { object valueNo1 = Get(recordNo1); if (valueNo1 is IComparable) { - if (value.GetType() == valueNo1.GetType()) + if (value!.GetType() == valueNo1.GetType()) return ((IComparable)valueNo1).CompareTo(value); } @@ -87,7 +87,7 @@ namespace System.Data.Common } - private int CompareTo(object valueNo1, object valueNo2) + private int CompareTo(object? valueNo1, object? valueNo2) { if (valueNo1 == null) return -1; @@ -159,8 +159,8 @@ namespace System.Data.Common return 0; } default: - valueNo1 = valueNo1.ToString(); - valueNo2 = valueNo2.ToString(); + valueNo1 = valueNo1.ToString()!; + valueNo2 = valueNo2.ToString()!; break; } return ((IComparable)valueNo1).CompareTo(valueNo2); @@ -174,7 +174,7 @@ namespace System.Data.Common public override object Get(int recordNo) { - object value = _values[recordNo]; + object? value = _values[recordNo]; if (null != value) { return value; @@ -316,7 +316,7 @@ namespace System.Data.Common } if (type == typeof(Type)) { - return Type.GetType(s); + return Type.GetType(s)!; } if (type == typeof(Guid)) { @@ -330,7 +330,7 @@ namespace System.Data.Common if (_implementsIXmlSerializable) { - object Obj = System.Activator.CreateInstance(_dataType, true); + object Obj = System.Activator.CreateInstance(_dataType, true)!; StringReader strReader = new StringReader(s); using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) { @@ -348,13 +348,13 @@ namespace System.Data.Common [MethodImpl(MethodImplOptions.NoInlining)] public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) { - object retValue = null; + object? retValue = null; bool isBaseCLRType = false; bool legacyUDT = false; // in 1.0 and 1.1 we used to call ToString on CDT obj. so if we have the same case // we need to handle the case when we have column type as object. if (null == xmlAttrib) { // this means type implements IXmlSerializable - Type type = null; + Type? type = null; string typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); if (typeName == null || typeName.Length == 0) { // No CDT polumorphism @@ -405,7 +405,7 @@ namespace System.Data.Common throw ExceptionBuilder.CanNotDeserializeObjectType(); if (!isBaseCLRType) { - retValue = System.Activator.CreateInstance(type, true); + retValue = System.Activator.CreateInstance(type, true)!; Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer"); ((IXmlSerializable)retValue).ReadXml(xmlReader); } @@ -425,7 +425,7 @@ namespace System.Data.Common } else { - retValue = Convert.FromBase64String(retValue.ToString()); + retValue = Convert.FromBase64String(retValue.ToString()!); } } xmlReader.Read(); @@ -438,7 +438,7 @@ namespace System.Data.Common XmlSerializer deserializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib); retValue = deserializerWithRootAttribute.Deserialize(xmlReader); } - return retValue; + return retValue!; } public override string ConvertObjectToXml(object value) @@ -453,7 +453,7 @@ namespace System.Data.Common } if ((type == typeof(Type)) || ((type == typeof(object)) && (value is Type))) { - return ((Type)value).AssemblyQualifiedName; + return ((Type)value).AssemblyQualifiedName!; } if (!IsTypeCustomType(value.GetType())) @@ -463,7 +463,7 @@ namespace System.Data.Common if (Type.GetTypeCode(value.GetType()) != TypeCode.Object) { - return value.ToString(); + return value.ToString()!; } StringWriter strwriter = new StringWriter(FormatProvider); @@ -481,7 +481,7 @@ namespace System.Data.Common return strwriter.ToString(); } - public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) + public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { if (null == xmlAttrib) { // implements IXmlSerializable @@ -502,14 +502,13 @@ namespace System.Data.Common protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { - object[] typedStore = (object[])store; + object?[] typedStore = (object?[])store; typedStore[storeIndex] = _values[record]; bool isNull = IsNull(record); nullbits.Set(storeIndex, isNull); - if (!isNull && (typedStore[storeIndex] is DateTime)) + if (!isNull && (typedStore[storeIndex] is DateTime dt)) { - DateTime dt = (DateTime)typedStore[storeIndex]; if (dt.Kind == DateTimeKind.Local) { typedStore[storeIndex] = DateTime.SpecifyKind(dt.ToUniversalTime(), DateTimeKind.Local); @@ -522,19 +521,15 @@ namespace System.Data.Common _values = (object[])store; for (int i = 0; i < _values.Length; i++) { - if (_values[i] is DateTime) + if (_values[i] is DateTime dt && dt.Kind == DateTimeKind.Local) { - DateTime dt = (DateTime)_values[i]; - if (dt.Kind == DateTimeKind.Local) - { - _values[i] = (DateTime.SpecifyKind(dt, DateTimeKind.Utc)).ToLocalTime(); - } + _values[i] = (DateTime.SpecifyKind(dt, DateTimeKind.Utc)).ToLocalTime(); } } } private static readonly object s_tempAssemblyCacheLock = new object(); - private static Dictionary, XmlSerializer> s_tempAssemblyCache; + private static Dictionary, XmlSerializer>? s_tempAssemblyCache; private static readonly XmlSerializerFactory s_serializerFactory = new XmlSerializerFactory(); /// @@ -566,11 +561,11 @@ namespace System.Data.Common internal static XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute attribute) { - XmlSerializer serializer = null; + XmlSerializer? serializer = null; KeyValuePair key = new KeyValuePair(type, attribute); // _tempAssemblyCache is a readonly instance, lock on write to copy & add then replace the original instance. - Dictionary, XmlSerializer> cache = s_tempAssemblyCache; + Dictionary, XmlSerializer>? cache = s_tempAssemblyCache; if ((null == cache) || !cache.TryGetValue(key, out serializer)) { // not in cache, try again with lock because it may need to grow lock (s_tempAssemblyCacheLock) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs index 42137ea..a2ef4bf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatedEventArgs.cs @@ -12,10 +12,10 @@ namespace System.Data.Common private readonly IDbCommand _command; private StatementType _statementType; private readonly DataTableMapping _tableMapping; - private Exception _errors; + private Exception? _errors; private DataRow _dataRow; - private DataRow[] _dataRows; + private DataRow[]? _dataRows; private UpdateStatus _status; // UpdateStatus.Continue; /*0*/ private int _recordsAffected; @@ -47,7 +47,7 @@ namespace System.Data.Common } } - public Exception Errors + public Exception? Errors { get { @@ -75,7 +75,7 @@ namespace System.Data.Common } } - internal DataRow[] Rows + internal DataRow[]? Rows { get { @@ -87,7 +87,7 @@ namespace System.Data.Common { get { - DataRow[] dataRows = _dataRows; + DataRow[]? dataRows = _dataRows; return ((null != dataRows) ? dataRows.Length : ((null != _dataRow) ? 1 : 0)); } } @@ -153,7 +153,7 @@ namespace System.Data.Common public void CopyToRows(DataRow[] array, int arrayIndex) { - DataRow[] dataRows = _dataRows; + DataRow[]? dataRows = _dataRows; if (null != dataRows) { dataRows.CopyTo(array, arrayIndex); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatingEventArgs.cs b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatingEventArgs.cs index d81db1f..16dbb9b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatingEventArgs.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/RowUpdatingEventArgs.cs @@ -5,15 +5,15 @@ namespace System.Data.Common { public class RowUpdatingEventArgs : EventArgs { - private IDbCommand _command; + private IDbCommand? _command; private readonly StatementType _statementType; private readonly DataTableMapping _tableMapping; - private Exception _errors; + private Exception? _errors; private readonly DataRow _dataRow; private UpdateStatus _status; - public RowUpdatingEventArgs(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) + public RowUpdatingEventArgs(DataRow dataRow, IDbCommand? command, StatementType statementType, DataTableMapping tableMapping) { ADP.CheckArgumentNull(dataRow, nameof(dataRow)); ADP.CheckArgumentNull(tableMapping, nameof(tableMapping)); @@ -35,19 +35,19 @@ namespace System.Data.Common _tableMapping = tableMapping; } - protected virtual IDbCommand BaseCommand + protected virtual IDbCommand? BaseCommand { get { return _command; } set { _command = value; } } - public IDbCommand Command + public IDbCommand? Command { get { return BaseCommand; } set { BaseCommand = value; } } - public Exception Errors + public Exception? Errors { get { return _errors; } set { _errors = value; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs index 79d5987..b6ddd9f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SByteStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const sbyte defaultValue = 0; - private sbyte[] _values; + private sbyte[] _values = default!; // Late-initialized public SByteStorage(DataColumn column) : base(column, typeof(sbyte), defaultValue, StorageType.SByte) @@ -129,12 +129,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -162,7 +162,7 @@ namespace System.Data.Common //return(valueNo1 - valueNo2); // copied from SByte.CompareTo(SByte) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -185,7 +185,7 @@ namespace System.Data.Common //return(valueNo1 - valueNo2); // copied from SByte.CompareTo(SByte) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs index 1e1027c..b01eeb5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs @@ -474,18 +474,18 @@ namespace System.Data.Common case StorageType.BigInteger: break; default: - IConvertible iconvertible = (value as IConvertible); + IConvertible? iconvertible = (value as IConvertible); if (null != iconvertible) { return iconvertible.ToString(formatProvider); } // catch additional classes like Guid - IFormattable iformattable = (value as IFormattable); + IFormattable? iformattable = (value as IFormattable); if (null != iformattable) { return iformattable.ToString(null, formatProvider); } - return value.ToString(); + return value.ToString()!; } } else if (StorageType.TimeSpan == stype) @@ -722,18 +722,18 @@ namespace System.Data.Common case StorageType.DateTimeOffset: return XmlConvert.ToString((DateTimeOffset)value); default: - IConvertible iconvertible = (value as IConvertible); + IConvertible? iconvertible = (value as IConvertible); if (null != iconvertible) { return iconvertible.ToString(System.Globalization.CultureInfo.InvariantCulture); } // catch additional classes like Guid - IFormattable iformattable = (value as IFormattable); + IFormattable? iformattable = (value as IFormattable); if (null != iformattable) { return iformattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture); } - return value.ToString(); + return value.ToString()!; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs index 99bed48..ce27245 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlBinaryStorage : DataStorage { - private SqlBinary[] _values; + private SqlBinary[] _values = default!; // Late-initialized public SqlBinaryStorage(DataColumn column) : base(column, typeof(SqlBinary), SqlBinary.Null, SqlBinary.Null, StorageType.SqlBinary) { @@ -24,12 +24,12 @@ namespace System.Data.Common { switch (kind) { - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: int count = 0; @@ -53,12 +53,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlBinary)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs index a9666c0..8b15f07 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLByteStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlByteStorage : DataStorage { - private SqlByte[] _values; + private SqlByte[] _values = default!; // Late-initialized public SqlByteStorage(DataColumn column) : base(column, typeof(SqlByte), SqlByte.Null, SqlByte.Null, StorageType.SqlByte) @@ -133,12 +133,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: count = 0; @@ -162,12 +162,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlByte)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs index bca1f5c..76ba394 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBytesStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlBytesStorage : DataStorage { - private SqlBytes[] _values; + private SqlBytes[] _values = default!; // Late-initialized public SqlBytesStorage(DataColumn column) : base(column, typeof(SqlBytes), SqlBytes.Null, SqlBytes.Null, StorageType.SqlBytes) @@ -25,12 +25,12 @@ namespace System.Data.Common { switch (kind) { - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: int count = 0; @@ -54,7 +54,7 @@ namespace System.Data.Common return 0; } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { return 0; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs index a40c5a9..74dc032 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLCharsStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlCharsStorage : DataStorage { - private SqlChars[] _values; + private SqlChars[] _values = default!; // Late-initialized public SqlCharsStorage(DataColumn column) : base(column, typeof(SqlChars), SqlChars.Null, SqlChars.Null, StorageType.SqlChars) @@ -25,12 +25,12 @@ namespace System.Data.Common { switch (kind) { - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: int count = 0; @@ -55,7 +55,7 @@ namespace System.Data.Common return 0; } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { // throw ExceptionBuilder.IComparableNotDefined; return 0; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs index bcf012bc..e36e4e0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDateTimeStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlDateTimeStorage : DataStorage { - private SqlDateTime[] _values; + private SqlDateTime[] _values = default!; // Late-initialized public SqlDateTimeStorage(DataColumn column) : base(column, typeof(SqlDateTime), SqlDateTime.Null, SqlDateTime.Null, StorageType.SqlDateTime) @@ -60,12 +60,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: int count = 0; @@ -89,12 +89,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlDateTime)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs index a22cb7e..9245967 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDecimalStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlDecimalStorage : DataStorage { - private SqlDecimal[] _values; + private SqlDecimal[] _values = default!; // Late-initialized public SqlDecimalStorage(DataColumn column) : base(column, typeof(SqlDecimal), SqlDecimal.Null, SqlDecimal.Null, StorageType.SqlDecimal) @@ -133,12 +133,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) @@ -161,12 +161,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlDecimal)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs index 3855c15..df041e6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLDoubleStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlDoubleStorage : DataStorage { - private SqlDouble[] _values; + private SqlDouble[] _values = default!; // Late-initialized public SqlDoubleStorage(DataColumn column) : base(column, typeof(SqlDouble), SqlDouble.Null, SqlDouble.Null, StorageType.SqlDouble) @@ -133,12 +133,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: count = 0; @@ -162,12 +162,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlDouble)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs index f4cae37..bb91efa 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLGuidStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlGuidStorage : DataStorage { - private SqlGuid[] _values; + private SqlGuid[] _values = default!; // Late-initialized public SqlGuidStorage(DataColumn column) : base(column, typeof(SqlGuid), SqlGuid.Null, SqlGuid.Null, StorageType.SqlGuid) @@ -25,12 +25,12 @@ namespace System.Data.Common { switch (kind) { - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: int count = 0; @@ -54,12 +54,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlGuid)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs index 7e7adac..17f1aac 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt16Storage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlInt16Storage : DataStorage { - private SqlInt16[] _values; + private SqlInt16[] _values = default!; // Late-initialized public SqlInt16Storage(DataColumn column) : base(column, typeof(SqlInt16), SqlInt16.Null, SqlInt16.Null, StorageType.SqlInt16) @@ -133,12 +133,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: count = 0; @@ -162,12 +162,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlInt16)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs index 5f341fa..dd48d02 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt32Storage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlInt32Storage : DataStorage { - private SqlInt32[] _values; + private SqlInt32[] _values = default!; // Late-initialized public SqlInt32Storage(DataColumn column) : base(column, typeof(SqlInt32), SqlInt32.Null, SqlInt32.Null, StorageType.SqlInt32) @@ -133,12 +133,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -162,12 +162,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlInt32)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs index 8a97f72..2c9fa58 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLInt64Storage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlInt64Storage : DataStorage { - private SqlInt64[] _values; + private SqlInt64[] _values = default!; public SqlInt64Storage(DataColumn column) : base(column, typeof(SqlInt64), SqlInt64.Null, SqlInt64.Null, StorageType.SqlInt64) @@ -134,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; // no data => null + return null!; // no data => null case AggregateType.Count: count = 0; @@ -163,12 +163,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlInt64)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs index 8d50857e..a036989 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLMoneyStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlMoneyStorage : DataStorage { - private SqlMoney[] _values; + private SqlMoney[] _values = default!; // Late-initialized public SqlMoneyStorage(DataColumn column) : base(column, typeof(SqlMoney), SqlMoney.Null, SqlMoney.Null, StorageType.SqlMoney) @@ -133,12 +133,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -162,12 +162,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlMoney)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs index f7de65a..7a492b2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLSingleStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlSingleStorage : DataStorage { - private SqlSingle[] _values; + private SqlSingle[] _values = default!; // Late-initialized public SqlSingleStorage(DataColumn column) : base(column, typeof(SqlSingle), SqlSingle.Null, SqlSingle.Null, StorageType.SqlSingle) @@ -131,12 +131,12 @@ namespace System.Data.Common return max; return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -160,12 +160,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlSingle)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs index 56d27bd..7e8094c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLStringStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlStringStorage : DataStorage { - private SqlString[] _values; + private SqlString[] _values = default!; // Late-initialized public SqlStringStorage(DataColumn column) : base(column, typeof(SqlString), SqlString.Null, SqlString.Null, StorageType.SqlString) @@ -109,12 +109,13 @@ namespace System.Data.Common return _table.Compare(valueNo1.Value, valueNo2.Value); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return Compare(_values[recordNo], (SqlString)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs index 74b5427..4bfadc6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQlBooleanStorage.cs @@ -12,7 +12,7 @@ namespace System.Data.Common { internal sealed class SqlBooleanStorage : DataStorage { - private SqlBoolean[] _values; + private SqlBoolean[] _values = default!; // Late-initialized public SqlBooleanStorage(DataColumn column) : base(column, typeof(SqlBoolean), SqlBoolean.Null, SqlBoolean.Null, StorageType.SqlBoolean) @@ -87,12 +87,13 @@ namespace System.Data.Common return _values[recordNo1].CompareTo(_values[recordNo2]); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { + Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlBoolean)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (null != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs index d2630c2..3b10386 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SingleStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const float defaultValue = 0.0f; - private float[] _values; + private float[] _values = default!; // Late-initialized public SingleStorage(DataColumn column) : base(column, typeof(float), defaultValue, StorageType.Single) @@ -130,12 +130,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -162,7 +162,7 @@ namespace System.Data.Common return valueNo1.CompareTo(valueNo2); // not simple, checks Nan } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -184,7 +184,7 @@ namespace System.Data.Common return valueNo1.CompareTo((float)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs index 83825e4..2681daf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs @@ -15,7 +15,7 @@ namespace System.Data.Common { internal sealed class SqlUdtStorage : DataStorage { - private object[] _values; + private object[] _values = default!; // Late-initialized private readonly bool _implementsIXmlSerializable; private readonly bool _implementsIComparable; @@ -36,19 +36,20 @@ namespace System.Data.Common // to support oracle types and other INUllable types that have static Null as field internal static object GetStaticNullForUdtType(Type type) => s_typeToNull.GetOrAdd(type, t => { - PropertyInfo propInfo = type.GetProperty("Null", BindingFlags.Public | BindingFlags.Static); + // TODO: Is it OK for the null value of a UDT to be null? For now annotating is non-nullable. + PropertyInfo? propInfo = type.GetProperty("Null", BindingFlags.Public | BindingFlags.Static); if (propInfo != null) { - return propInfo.GetValue(null, null); + return propInfo.GetValue(null, null)!; } - FieldInfo fieldInfo = type.GetField("Null", BindingFlags.Public | BindingFlags.Static); + FieldInfo fieldInfo = type.GetField("Null", BindingFlags.Public | BindingFlags.Static)!; if (fieldInfo != null) { - return fieldInfo.GetValue(null); + return fieldInfo.GetValue(null)!; } - throw ExceptionBuilder.INullableUDTwithoutStaticNull(type.AssemblyQualifiedName); + throw ExceptionBuilder.INullableUDTwithoutStaticNull(type.AssemblyQualifiedName!); }); public override bool IsNull(int record) @@ -66,7 +67,7 @@ namespace System.Data.Common return (CompareValueTo(recordNo1, _values[recordNo2])); } - public override int CompareValueTo(int recordNo1, object value) + public override int CompareValueTo(int recordNo1, object? value) { if (DBNull.Value == value) { @@ -84,7 +85,7 @@ namespace System.Data.Common return nullableValue.IsNull ? 0 : 1; // left may be null, right is null } - throw ExceptionBuilder.IComparableNotImplemented(_dataType.AssemblyQualifiedName); + throw ExceptionBuilder.IComparableNotImplemented(_dataType.AssemblyQualifiedName!); } public override void Copy(int recordNo1, int recordNo2) @@ -146,7 +147,7 @@ namespace System.Data.Common { if (_implementsIXmlSerializable) { - object Obj = System.Activator.CreateInstance(_dataType, true); + object Obj = System.Activator.CreateInstance(_dataType, true)!; string tempStr = string.Concat("", s, ""); // this is done since you can give fragmet to reader StringReader strReader = new StringReader(tempStr); @@ -175,11 +176,11 @@ namespace System.Data.Common string xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type if (null != xsdTypeName) { - typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName; + typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName!; } } - Type type = (typeName == null) ? _dataType : Type.GetType(typeName); - object Obj = System.Activator.CreateInstance(type, true); + Type type = (typeName == null) ? _dataType : Type.GetType(typeName)!; + object Obj = System.Activator.CreateInstance(type, true)!; Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer"); ((IXmlSerializable)Obj).ReadXml(xmlReader); return Obj; @@ -210,7 +211,7 @@ namespace System.Data.Common return (strwriter.ToString()); } - public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) + public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { if (null == xmlAttrib) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs index f5918e8..fa919b3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/StringStorage.cs @@ -9,7 +9,7 @@ namespace System.Data.Common // The string storage does not use BitArrays in DataStorage internal sealed class StringStorage : DataStorage { - private string[] _values; + private string?[] _values = default!; // Late-initialized public StringStorage(DataColumn column) : base(column, typeof(string), string.Empty, StorageType.String) @@ -71,7 +71,7 @@ namespace System.Data.Common int count = 0; for (i = 0; i < recordNos.Length; i++) { - object value = _values[recordNos[i]]; + object? value = _values[recordNos[i]]; if (value != null) count++; } @@ -82,10 +82,10 @@ namespace System.Data.Common public override int Compare(int recordNo1, int recordNo2) { - string valueNo1 = _values[recordNo1]; - string valueNo2 = _values[recordNo2]; + string? valueNo1 = _values[recordNo1]; + string? valueNo2 = _values[recordNo2]; - if (valueNo1 == (object)valueNo2) + if (valueNo1 == (object?)valueNo2) return 0; if (valueNo1 == null) @@ -96,11 +96,11 @@ namespace System.Data.Common return _table.Compare(valueNo1, valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(recordNo != -1, "Invalid (-1) parameter: 'recordNo'"); Debug.Assert(null != value, "null value"); - string valueNo1 = _values[recordNo]; + string? valueNo1 = _values[recordNo]; if (null == valueNo1) { @@ -120,13 +120,13 @@ namespace System.Data.Common return _table.Compare(valueNo1, (string)value); } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { if (null != value) { - value = value.ToString(); + value = value.ToString()!; } else { @@ -143,7 +143,7 @@ namespace System.Data.Common public override object Get(int recordNo) { - string value = _values[recordNo]; + string? value = _values[recordNo]; if (null != value) { @@ -154,7 +154,7 @@ namespace System.Data.Common public override int GetStringLength(int record) { - string value = _values[record]; + string? value = _values[record]; return ((null != value) ? value.Length : 0); } @@ -203,14 +203,14 @@ namespace System.Data.Common protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { - string[] typedStore = (string[])store; + string?[] typedStore = (string?[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { - _values = (string[])store; + _values = (string?[])store; // SetNullStorage(nullbits); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs index dd886b1..5ce9037 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/TimeSpanStorage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private static readonly TimeSpan s_defaultValue = TimeSpan.Zero; - private TimeSpan[] _values; + private TimeSpan[] _values = default!; // Late-initialized public TimeSpanStorage(DataColumn column) : base(column, typeof(TimeSpan), s_defaultValue, StorageType.TimeSpan) @@ -56,12 +56,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -80,7 +80,7 @@ namespace System.Data.Common { return TimeSpan.FromTicks((long)Math.Round(sum)); } - return null; + return null!; // TODO: This is incorrect, should be DBNull.Value } case AggregateType.Mean: @@ -98,7 +98,7 @@ namespace System.Data.Common { return TimeSpan.FromTicks((long)Math.Round(meanSum / meanCount)); } - return null; + return null!; // TODO: This is incorrect, should be DBNull.Value } case AggregateType.StDev: @@ -132,7 +132,7 @@ namespace System.Data.Common } return TimeSpan.FromTicks((long)stDev); } - return null; + return null!; // TODO: This is incorrect, should be DBNull.Value } } } @@ -157,7 +157,7 @@ namespace System.Data.Common return TimeSpan.Compare(valueNo1, valueNo2); } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -202,7 +202,7 @@ namespace System.Data.Common } } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs index 5663a43..25d3b7c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const ushort DefaultValue = ushort.MinValue; - private ushort[] _values; + private ushort[] _values = default!; // Late-initialized public UInt16Storage(DataColumn column) : base(column, typeof(ushort), DefaultValue, StorageType.UInt16) @@ -134,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -177,7 +177,7 @@ namespace System.Data.Common return valueNo1 - valueNo2; // copied from UInt16.CompareTo(UInt16) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -196,7 +196,7 @@ namespace System.Data.Common //return ((int)valueNo1 - (int)valueNo2); // copied from UInt16.CompareTo(UInt16) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs index 406e91e..b801841 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/UInt32Storage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const uint DefaultValue = uint.MinValue; - private uint[] _values; + private uint[] _values = default!; // Late-initialized public UInt32Storage(DataColumn column) : base(column, typeof(uint), DefaultValue, StorageType.UInt32) @@ -134,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: count = 0; @@ -176,7 +176,7 @@ namespace System.Data.Common return (valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt32.CompareTo(UInt32) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -195,7 +195,7 @@ namespace System.Data.Common //return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt32.CompareTo(UInt32) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs index 11f71ec..9dc67b2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/UInt64Storage.cs @@ -10,7 +10,7 @@ namespace System.Data.Common { private const ulong DefaultValue = ulong.MinValue; - private ulong[] _values; + private ulong[] _values = default!; // Late-initialized public UInt64Storage(DataColumn column) : base(column, typeof(ulong), DefaultValue, StorageType.UInt64) @@ -134,12 +134,12 @@ namespace System.Data.Common } return _nullValue; - case AggregateType.First: + case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } - return null; + return null!; case AggregateType.Count: return base.Aggregate(records, kind); @@ -167,7 +167,7 @@ namespace System.Data.Common return (valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt64.CompareTo(UInt64) } - public override int CompareValueTo(int recordNo, object value) + public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); @@ -186,7 +186,7 @@ namespace System.Data.Common //return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt64.CompareTo(UInt64) } - public override object ConvertValue(object value) + public override object ConvertValue(object? value) { if (_nullValue != value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/identifiercase.cs b/src/libraries/System.Data.Common/src/System/Data/Common/identifiercase.cs index d8c17f4..6092fd4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/identifiercase.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/identifiercase.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data.Common { public enum IdentifierCase diff --git a/src/libraries/System.Data.Common/src/System/Data/Constraint.cs b/src/libraries/System.Data.Common/src/System/Data/Constraint.cs index 081e75e..3667e10 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Constraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Constraint.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data @@ -15,9 +16,9 @@ namespace System.Data { private string _schemaName = string.Empty; private bool _inCollection; - private DataSet _dataSet; + private DataSet? _dataSet; internal string _name = string.Empty; - internal PropertyCollection _extendedProperties; + internal PropertyCollection? _extendedProperties; internal Constraint() { } @@ -25,6 +26,7 @@ namespace System.Data /// The name of this constraint within the . /// [DefaultValue("")] + [AllowNull] public virtual string ConstraintName { get { return _name; } @@ -76,14 +78,14 @@ namespace System.Data set { _inCollection = value; - _dataSet = value ? Table.DataSet : null; + _dataSet = value ? Table!.DataSet : null; } } /// /// Gets the to which the constraint applies. /// - public abstract DataTable Table { get; } + public abstract DataTable? Table { get; } /// /// Gets the collection of customized user information. @@ -94,8 +96,8 @@ namespace System.Data internal abstract bool ContainsColumn(DataColumn column); internal abstract bool CanEnableConstraint(); - internal abstract Constraint Clone(DataSet destination); - internal abstract Constraint Clone(DataSet destination, bool ignoreNSforTableLookup); + internal abstract Constraint? Clone(DataSet destination); + internal abstract Constraint? Clone(DataSet destination, bool ignoreNSforTableLookup); internal void CheckConstraint() { @@ -127,7 +129,7 @@ namespace System.Data /// Gets the to which this constraint belongs. /// [CLSCompliant(false)] - protected virtual DataSet _DataSet => _dataSet; + protected virtual DataSet? _DataSet => _dataSet; /// /// Sets the constraint's . diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs index 1bb86f6..806bab3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Collections; using System.ComponentModel; +using System.Resources; namespace System.Data { @@ -17,8 +18,8 @@ namespace System.Data private readonly ArrayList _list = new ArrayList(); private int _defaultNameIndex = 1; - private CollectionChangeEventHandler _onCollectionChanged; - private Constraint[] _delayLoadingConstraints; + private CollectionChangeEventHandler? _onCollectionChanged; + private Constraint[]? _delayLoadingConstraints; private bool _fLoadForeignKeyConstraintsOnly; /// @@ -45,7 +46,7 @@ namespace System.Data { if (index >= 0 && index < List.Count) { - return (Constraint)List[index]; + return (Constraint)List[index]!; } throw ExceptionBuilder.ConstraintOutOfRange(index); } @@ -59,16 +60,16 @@ namespace System.Data /// /// Gets the from the collection with the specified name. /// - public Constraint this[string name] + public Constraint? this[string? name] { get { int index = InternalIndexOf(name); if (index == -2) { - throw ExceptionBuilder.CaseInsensitiveNameConflict(name); + throw ExceptionBuilder.CaseInsensitiveNameConflict(name!); } - return (index < 0) ? null : (Constraint)List[index]; + return (index < 0) ? null : (Constraint)List[index]!; } } @@ -86,9 +87,9 @@ namespace System.Data } // It is an error if we find an equivalent constraint already in collection - if (FindConstraint(constraint) != null) + if (FindConstraint(constraint) is { } matchedConstraint) { - throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName); + throw ExceptionBuilder.DuplicateConstraint(matchedConstraint.ConstraintName); } if (1 < _table.NestedParentRelations.Length) @@ -115,7 +116,7 @@ namespace System.Data ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint; if (addUniqueWhenAddingForeign) { - UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); + UniqueConstraint? key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); if (key == null) { if (constraint.ConstraintName.Length == 0) @@ -147,7 +148,7 @@ namespace System.Data /// specified array of /// objects and adds it to the collection. /// - public Constraint Add(string name, DataColumn[] columns, bool primaryKey) + public Constraint Add(string? name, DataColumn[] columns, bool primaryKey) { UniqueConstraint constraint = new UniqueConstraint(name, columns); Add(constraint); @@ -160,7 +161,7 @@ namespace System.Data /// Constructs a new using the /// specified and adds it to the collection. /// - public Constraint Add(string name, DataColumn column, bool primaryKey) + public Constraint Add(string? name, DataColumn column, bool primaryKey) { UniqueConstraint constraint = new UniqueConstraint(name, column); Add(constraint); @@ -175,7 +176,7 @@ namespace System.Data /// specified parent and child /// columns and adds the constraint to the collection. /// - public Constraint Add(string name, DataColumn primaryKeyColumn, DataColumn foreignKeyColumn) + public Constraint Add(string? name, DataColumn primaryKeyColumn, DataColumn foreignKeyColumn) { ForeignKeyConstraint constraint = new ForeignKeyConstraint(name, primaryKeyColumn, foreignKeyColumn); Add(constraint); @@ -186,14 +187,14 @@ namespace System.Data /// Constructs a new with the specified parent columns and /// child columns and adds the constraint to the collection. /// - public Constraint Add(string name, DataColumn[] primaryKeyColumns, DataColumn[] foreignKeyColumns) + public Constraint Add(string? name, DataColumn[] primaryKeyColumns, DataColumn[] foreignKeyColumns) { ForeignKeyConstraint constraint = new ForeignKeyConstraint(name, primaryKeyColumns, foreignKeyColumns); Add(constraint); return constraint; } - public void AddRange(Constraint[] constraints) + public void AddRange(Constraint[]? constraints) { if (_table.fInitInProgress) { @@ -246,7 +247,7 @@ namespace System.Data private bool AutoGenerated(Constraint constraint) { - ForeignKeyConstraint fk = (constraint as ForeignKeyConstraint); + ForeignKeyConstraint? fk = (constraint as ForeignKeyConstraint); if (null != fk) { return XmlTreeGen.AutoGenerated(fk, false); @@ -262,7 +263,7 @@ namespace System.Data /// Occurs when the is changed through additions or /// removals. /// - public event CollectionChangeEventHandler CollectionChanged + public event CollectionChangeEventHandler? CollectionChanged { add { @@ -444,12 +445,12 @@ namespace System.Data try { // this will smartly add and remove the appropriate tables. - BaseGroupSwitch(constraints, oldLength, null, 0); + BaseGroupSwitch(constraints, oldLength, Array.Empty(), 0); } catch (Exception e) when (Common.ADP.IsCatchableOrSecurityExceptionType(e)) { // something messed up. restore to original state. - BaseGroupSwitch(null, 0, constraints, oldLength); + BaseGroupSwitch(Array.Empty(), 0, constraints, oldLength); List.Clear(); for (int i = 0; i < oldLength; i++) { @@ -465,19 +466,19 @@ namespace System.Data /// /// Indicates whether the , specified by name, exists in the collection. /// - public bool Contains(string name) + public bool Contains(string? name) { return (InternalIndexOf(name) >= 0); } - internal bool Contains(string name, bool caseSensitive) + internal bool Contains(string? name, bool caseSensitive) { if (!caseSensitive) return Contains(name); int index = InternalIndexOf(name); if (index < 0) return false; - return (name == ((Constraint)List[index]).ConstraintName); + return (name == ((Constraint)List[index]!).ConstraintName); } public void CopyTo(Constraint[] array, int index) @@ -490,20 +491,20 @@ namespace System.Data throw ExceptionBuilder.InvalidOffsetLength(); for (int i = 0; i < _list.Count; ++i) { - array[index + i] = (Constraint)_list[i]; + array[index + i] = (Constraint)_list[i]!; } } /// /// Returns a matching constraint object. /// - internal Constraint FindConstraint(Constraint constraint) + internal Constraint? FindConstraint(Constraint? constraint) { int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) { - if (((Constraint)List[i]).Equals(constraint)) - return (Constraint)List[i]; + if (((Constraint)List[i]!).Equals(constraint)) + return (Constraint)List[i]!; } return null; } @@ -511,12 +512,12 @@ namespace System.Data /// /// Returns a matching constraint object. /// - internal UniqueConstraint FindKeyConstraint(DataColumn[] columns) + internal UniqueConstraint? FindKeyConstraint(DataColumn[] columns) { int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) { - UniqueConstraint constraint = (List[i] as UniqueConstraint); + UniqueConstraint? constraint = (List[i] as UniqueConstraint); if ((null != constraint) && CompareArrays(constraint.Key.ColumnsReference, columns)) { return constraint; @@ -528,12 +529,12 @@ namespace System.Data /// /// Returns a matching constraint object. /// - internal UniqueConstraint FindKeyConstraint(DataColumn column) + internal UniqueConstraint? FindKeyConstraint(DataColumn column) { int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) { - UniqueConstraint constraint = (List[i] as UniqueConstraint); + UniqueConstraint? constraint = (List[i] as UniqueConstraint); if ((null != constraint) && (constraint.Key.ColumnsReference.Length == 1) && (constraint.Key.ColumnsReference[0] == column)) return constraint; } @@ -543,12 +544,12 @@ namespace System.Data /// /// Returns a matching constraint object. /// - internal ForeignKeyConstraint FindForeignKeyConstraint(DataColumn[] parentColumns, DataColumn[] childColumns) + internal ForeignKeyConstraint? FindForeignKeyConstraint(DataColumn[] parentColumns, DataColumn[] childColumns) { int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) { - ForeignKeyConstraint constraint = (List[i] as ForeignKeyConstraint); + ForeignKeyConstraint? constraint = (List[i] as ForeignKeyConstraint); if ((null != constraint) && CompareArrays(constraint.ParentKey.ColumnsReference, parentColumns) && CompareArrays(constraint.ChildKey.ColumnsReference, childColumns)) @@ -587,14 +588,14 @@ namespace System.Data /// /// Returns the index of the specified . /// - public int IndexOf(Constraint constraint) + public int IndexOf(Constraint? constraint) { if (null != constraint) { int count = Count; for (int i = 0; i < count; ++i) { - if (constraint == (Constraint)List[i]) + if (constraint == (Constraint)List[i]!) return i; } // didn't find the constraint @@ -605,7 +606,7 @@ namespace System.Data /// /// Returns the index of the , specified by name. /// - public int IndexOf(string constraintName) + public int IndexOf(string? constraintName) { int index = InternalIndexOf(constraintName); return (index < 0) ? -1 : index; @@ -615,7 +616,7 @@ namespace System.Data // >= 0: find the match // -1: No match // -2: At least two matches with different cases - internal int InternalIndexOf(string constraintName) + internal int InternalIndexOf(string? constraintName) { int cachedI = -1; if ((null != constraintName) && (0 < constraintName.Length)) @@ -624,7 +625,7 @@ namespace System.Data int result = 0; for (int i = 0; i < constraintCount; i++) { - Constraint constraint = (Constraint)List[i]; + Constraint constraint = (Constraint)List[i]!; result = NamesEqual(constraint.ConstraintName, constraintName, false, _table.Locale); if (result == 1) return i; @@ -668,9 +669,9 @@ namespace System.Data int constraintCount = List.Count; for (int i = 0; i < constraintCount; i++) { - if (NamesEqual(name, ((Constraint)List[i]).ConstraintName, true, _table.Locale) != 0) + if (NamesEqual(name, ((Constraint)List[i]!).ConstraintName, true, _table.Locale) != 0) { - throw ExceptionBuilder.DuplicateConstraintName(((Constraint)List[i]).ConstraintName); + throw ExceptionBuilder.DuplicateConstraintName(((Constraint)List[i]!).ConstraintName); } } if (NamesEqual(name, MakeName(_defaultNameIndex), true, _table.Locale) != 0) @@ -719,7 +720,7 @@ namespace System.Data /// public void Remove(string name) { - Constraint c = this[name]; + Constraint? c = this[name]; if (c == null) throw ExceptionBuilder.ConstraintNotInTheTable(name); Remove(c); @@ -765,7 +766,7 @@ namespace System.Data colCount = constr._columnNames.Length; parents = new DataColumn[colCount]; for (int j = 0; j < colCount; j++) - parents[j] = _table.Columns[constr._columnNames[j]]; + parents[j] = _table.Columns[constr._columnNames[j]]!; if (constr._bPrimaryKey) { if (_table._primaryKey != null) @@ -791,6 +792,8 @@ namespace System.Data continue; } + Debug.Assert(constr._parentTableName != null); + if (_table.DataSet == null) { _fLoadForeignKeyConstraintsOnly = true; @@ -803,10 +806,10 @@ namespace System.Data for (int j = 0; j < colCount; j++) { if (constr._parentTableNamespace == null) - parents[j] = _table.DataSet.Tables[constr._parentTableName].Columns[constr._parentColumnNames[j]]; + parents[j] = _table.DataSet.Tables[constr._parentTableName]!.Columns[constr._parentColumnNames[j]]!; else - parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace].Columns[constr._parentColumnNames[j]]; - childs[j] = _table.Columns[constr._childColumnNames[j]]; + parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace]!.Columns[constr._parentColumnNames[j]]!; + childs[j] = _table.Columns[constr._childColumnNames[j]]!; } ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(constr._constraintName, parents, childs); newConstraint.AcceptRejectRule = constr._acceptRejectRule; diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs index 9a33716..7a074f9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs @@ -39,7 +39,7 @@ namespace System.Data if (value is UniqueConstraint) { UniqueConstraint constr = (UniqueConstraint)value; - Reflection.ConstructorInfo ctor = typeof(UniqueConstraint).GetConstructor(new Type[] { typeof(string), typeof(string[]), typeof(bool) }); + Reflection.ConstructorInfo ctor = typeof(UniqueConstraint).GetConstructor(new Type[] { typeof(string), typeof(string[]), typeof(bool) })!; if (ctor != null) { return new InstanceDescriptor(ctor, new object[] { constr.ConstraintName, constr.ColumnNames, constr.IsPrimaryKey }); @@ -50,7 +50,7 @@ namespace System.Data ForeignKeyConstraint constr = (ForeignKeyConstraint)value; System.Reflection.ConstructorInfo ctor = typeof(ForeignKeyConstraint).GetConstructor(new Type[] { typeof(string), typeof(string), typeof(string[]), - typeof(string[]), typeof(AcceptRejectRule), typeof(Rule), typeof(Rule) }); + typeof(string[]), typeof(AcceptRejectRule), typeof(Rule), typeof(Rule) })!; if (ctor != null) { return new InstanceDescriptor(ctor, new object[] { constr.ConstraintName, constr.ParentKey.Table.TableName, constr.ParentColumnNames, diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs index d1d6754..f296e4a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintEnumerator.cs @@ -11,11 +11,11 @@ namespace System.Data /// internal class ConstraintEnumerator { - private IEnumerator _tables; - private IEnumerator _constraints; - private Constraint _currentObject; + private IEnumerator? _tables; + private IEnumerator? _constraints; + private Constraint? _currentObject; - public ConstraintEnumerator(DataSet dataSet) + public ConstraintEnumerator(DataSet? dataSet) { _tables = (dataSet != null) ? dataSet.Tables.GetEnumerator() : null; _currentObject = null; @@ -63,12 +63,12 @@ namespace System.Data protected virtual bool IsValidCandidate(Constraint constraint) => true; - protected Constraint CurrentObject => _currentObject; + protected Constraint? CurrentObject => _currentObject; } internal class ForeignKeyConstraintEnumerator : ConstraintEnumerator { - public ForeignKeyConstraintEnumerator(DataSet dataSet) : base(dataSet) { } + public ForeignKeyConstraintEnumerator(DataSet? dataSet) : base(dataSet) { } protected override bool IsValidCandidate(Constraint constraint) => constraint is ForeignKeyConstraint; @@ -99,7 +99,7 @@ namespace System.Data // this is the table to do comparisons against private readonly DataTable _table; - public ParentForeignKeyConstraintEnumerator(DataSet dataSet, DataTable inTable) : base(dataSet) + public ParentForeignKeyConstraintEnumerator(DataSet? dataSet, DataTable inTable) : base(dataSet) { _table = inTable; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs b/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs index 1a63dc9..1fd430e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DBConcurrencyException.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; namespace System.Data @@ -9,22 +10,22 @@ namespace System.Data [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class DBConcurrencyException : SystemException { - private DataRow[] _dataRows; + private DataRow[]? _dataRows; public DBConcurrencyException() : this(SR.ADP_DBConcurrencyExceptionMessage, null) { } - public DBConcurrencyException(string message) : this(message, null) + public DBConcurrencyException(string? message) : this(message, null) { } - public DBConcurrencyException(string message, Exception inner) : base(message, inner) + public DBConcurrencyException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.DBConcurrency; } - public DBConcurrencyException(string message, Exception inner, DataRow[] dataRows) : base(message, inner) + public DBConcurrencyException(string? message, Exception? inner, DataRow[]? dataRows) : base(message, inner) { HResult = HResults.DBConcurrency; _dataRows = dataRows; @@ -39,11 +40,12 @@ namespace System.Data base.GetObjectData(info, context); } - public DataRow Row + [DisallowNull] + public DataRow? Row { get { - DataRow[] rows = _dataRows; + DataRow[]? rows = _dataRows; return (((null != rows) && (0 < rows.Length)) ? rows[0] : null); } set @@ -56,7 +58,7 @@ namespace System.Data { get { - DataRow[] dataRows = _dataRows; + DataRow[]? dataRows = _dataRows; return ((null != dataRows) ? dataRows.Length : 0); } } @@ -68,7 +70,7 @@ namespace System.Data public void CopyToRows(DataRow[] array, int arrayIndex) { - DataRow[] dataRows = _dataRows; + DataRow[]? dataRows = _dataRows; if (null != dataRows) { dataRows.CopyTo(array, arrayIndex); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs index da6504c..1b09c0a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -14,6 +14,7 @@ using System.Threading; using System.Numerics; using System.Reflection; using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -26,18 +27,18 @@ namespace System.Data public class DataColumn : MarshalByValueComponent { private bool _allowNull = true; - private string _caption; + private string? _caption; private string _columnName; - private Type _dataType; + private Type _dataType = null!; // Always set in UpdateColumnType private StorageType _storageType; internal object _defaultValue = DBNull.Value; // DefaultValue Converter private DataSetDateTime _dateTimeMode = DataSetDateTime.UnspecifiedLocal; - private DataExpression _expression; + private DataExpression? _expression; private int _maxLength = -1; private int _ordinal = -1; private bool _readOnly; - internal Index _sortIndex; - internal DataTable _table; + internal Index? _sortIndex; + internal DataTable? _table; private bool _unique; internal MappingType _columnMapping = MappingType.Element; internal int _hashCode; @@ -51,20 +52,20 @@ namespace System.Data private bool _defaultValueIsNull = true; - internal List _dependentColumns; // list of columns whose expression consume values from this column - internal PropertyCollection _extendedProperties; + internal List? _dependentColumns; // list of columns whose expression consume values from this column + internal PropertyCollection? _extendedProperties; - private DataStorage _storage; + private DataStorage? _storage; /// represents current value to return, usage pattern is .get_Current then MoveAfter - private AutoIncrementValue _autoInc; + private AutoIncrementValue? _autoInc; // The _columnClass member is the class for the unfoliated virtual nodes in the XML. - internal string _columnUri; + internal string? _columnUri; private string _columnPrefix = string.Empty; - internal string _encodedColumnName; + internal string? _encodedColumnName; - internal SimpleType _simpleType; + internal SimpleType? _simpleType; private static int s_objectTypeCount; private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount); @@ -81,7 +82,7 @@ namespace System.Data /// Initializes a new instance of the class /// using the specified column name. /// - public DataColumn(string columnName) : this(columnName, typeof(string), null, MappingType.Element) + public DataColumn(string? columnName) : this(columnName, typeof(string), null, MappingType.Element) { } @@ -89,7 +90,7 @@ namespace System.Data /// Initializes a new instance of the class /// using the specified column name and data type. /// - public DataColumn(string columnName, Type dataType) : this(columnName, dataType, null, MappingType.Element) + public DataColumn(string? columnName, Type dataType) : this(columnName, dataType, null, MappingType.Element) { } @@ -98,7 +99,7 @@ namespace System.Data /// of the class /// using the specified name, data type, and expression. /// - public DataColumn(string columnName, Type dataType, string expr) : this(columnName, dataType, expr, MappingType.Element) + public DataColumn(string? columnName, Type dataType, string? expr) : this(columnName, dataType, expr, MappingType.Element) { } @@ -108,7 +109,7 @@ namespace System.Data /// the specified name, data type, expression, and value that determines whether the /// column is an attribute. /// - public DataColumn(string columnName, Type dataType, string expr, MappingType type) + public DataColumn(string? columnName, Type dataType, string? expr, MappingType type) { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" {0}, columnName='{1}', expr='{2}', type={3}", ObjectID, columnName, expr, type); @@ -125,7 +126,7 @@ namespace System.Data } _columnName = columnName ?? string.Empty; - SimpleType stype = SimpleType.CreateSimpleType(typeCode, dataType); + SimpleType? stype = SimpleType.CreateSimpleType(typeCode, dataType); if (null != stype) { SimpleType = stype; @@ -298,6 +299,7 @@ namespace System.Data /// Gets or sets /// the caption for this column. /// + [AllowNull] public string Caption { get { return (_caption != null) ? _caption : _columnName; } @@ -337,6 +339,7 @@ namespace System.Data /// [RefreshProperties(RefreshProperties.All)] [DefaultValue("")] + [AllowNull] public string ColumnName { get { return _columnName; } @@ -417,6 +420,7 @@ namespace System.Data internal int ObjectID => _objectID; [DefaultValue("")] + [AllowNull] public string Prefix { get { return _columnPrefix; } @@ -442,7 +446,7 @@ namespace System.Data // If the column type is string and it's value is empty, then the empty string is returned. // If the column type is not string, or the column type is string and the value is not empty string, then a non-empty string is returned // This method does not throw any formatting exceptions, since we can always format the field value to a string. - internal string GetColumnValueAsString(DataRow row, DataRowVersion version) + internal string? GetColumnValueAsString(DataRow row, DataRowVersion version) { object objValue = this[row.GetRecordFromVersion(version)]; @@ -464,7 +468,7 @@ namespace System.Data /// /// The internal expression object that computes the values. /// - internal DataExpression DataExpression => _expression; + internal DataExpression? DataExpression => _expression; /// /// The type of data stored in the column. @@ -472,6 +476,7 @@ namespace System.Data [DefaultValue(typeof(string))] [RefreshProperties(RefreshProperties.All)] [TypeConverter(typeof(ColumnTypeConverter))] + [AllowNull] public Type DataType { get { return _dataType; } @@ -517,7 +522,7 @@ namespace System.Data else if (typeof(string) == value) { // since string types can be null in value! DO NOT REMOVE THIS CHECK - _defaultValue = DefaultValue.ToString(); + _defaultValue = DefaultValue.ToString()!; } else if (typeof(SqlString) == value) { @@ -572,7 +577,7 @@ namespace System.Data AutoInc.Auto = inc.Auto; // recreate with correct datatype AutoInc.Seed = inc.Seed; AutoInc.Step = inc.Step; - if (_autoInc.DataType == inc.DataType) + if (_autoInc!.DataType == inc.DataType) { _autoInc.Current = inc.Current; } @@ -636,6 +641,7 @@ namespace System.Data /// Gets or sets the default value for the column when creating new rows. /// [TypeConverter(typeof(DefaultValueTypeConverter))] + [AllowNull] public object DefaultValue { get @@ -654,10 +660,10 @@ namespace System.Data } else if (_implementsINullable) { - PropertyInfo propInfo = _dataType.GetProperty("Null", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); + PropertyInfo propInfo = _dataType.GetProperty("Null", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)!; if (propInfo != null) { - _defaultValue = propInfo.GetValue(null, null); + _defaultValue = propInfo.GetValue(null, null)!; } } } @@ -695,7 +701,7 @@ namespace System.Data internal bool DefaultValueIsNull => _defaultValueIsNull; - internal void BindExpression() => DataExpression.Bind(_table); + internal void BindExpression() => DataExpression!.Bind(_table); /// /// Gets or sets the expression used to either filter rows, calculate the column's @@ -703,6 +709,7 @@ namespace System.Data /// [RefreshProperties(RefreshProperties.All)] [DefaultValue("")] + [AllowNull] public string Expression { get { return (_expression == null ? "" : _expression.Expression); } @@ -717,7 +724,7 @@ namespace System.Data try { - DataExpression newExpression = null; + DataExpression? newExpression = null; if (value.Length > 0) { DataExpression testExpression = new DataExpression(_table, value, _dataType); @@ -769,7 +776,7 @@ namespace System.Data HandleDependentColumnList(_expression, newExpression); //hold onto oldExpression in case of error applying new Expression. - DataExpression oldExpression = _expression; + DataExpression? oldExpression = _expression; _expression = newExpression; // because the column is attached to a table we need to re-calc values @@ -948,6 +955,7 @@ namespace System.Data } } + [AllowNull] public string Namespace { get @@ -1002,7 +1010,7 @@ namespace System.Data if (_ordinal != ordinal) { - _table.Columns.MoveTo(this, ordinal); + _table!.Columns.MoveTo(this, ordinal); } } @@ -1012,7 +1020,7 @@ namespace System.Data { if (Unique && _ordinal != -1 && ordinal == -1) { - UniqueConstraint key = _table.Constraints.FindKeyConstraint(this); + UniqueConstraint? key = _table!.Constraints.FindKeyConstraint(this); if (key != null) { _table.Constraints.Remove(key); @@ -1034,7 +1042,7 @@ namespace System.Data if (Unique) { UniqueConstraint key = new UniqueConstraint(this); - _table.Constraints.Add(key); + _table!.Constraints.Add(key); } } } @@ -1070,7 +1078,7 @@ namespace System.Data if (_sortIndex == null) { var indexDesc = new IndexField[] { new IndexField(this, false) }; - _sortIndex = _table.GetIndex(indexDesc, DataViewRowState.CurrentRows, null); + _sortIndex = _table!.GetIndex(indexDesc, DataViewRowState.CurrentRows, null); _sortIndex.AddRef(); } return _sortIndex; @@ -1082,13 +1090,14 @@ namespace System.Data /// [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public DataTable Table => _table; + public DataTable? Table => _table; /// /// Internal mechanism for changing the table pointer. /// - internal void SetTable(DataTable table) + internal void SetTable(DataTable? table) { + Debug.Assert(table != null || !Unique); if (_table != table) { if (Computed) @@ -1096,13 +1105,13 @@ namespace System.Data if ((table == null) || (!table.fInitInProgress && ((table.DataSet == null) || (!table.DataSet._fIsSchemaLoading && !table.DataSet._fInitInProgress)))) { // We need to re-bind all expression columns. - DataExpression.Bind(table); + DataExpression!.Bind(table); } } if (Unique && _table != null) { - UniqueConstraint constraint = table.Constraints.FindKeyConstraint(this); + UniqueConstraint? constraint = table!.Constraints.FindKeyConstraint(this); if (constraint != null) { table.Constraints.CanRemove(constraint, true); @@ -1113,7 +1122,7 @@ namespace System.Data } } - private DataRow GetDataRow(int index) => _table._recordManager[index]; + private DataRow GetDataRow(int index) => _table!._recordManager[index]; /// /// This is how data is pushed in and out of the column. @@ -1122,7 +1131,7 @@ namespace System.Data { get { - _table._recordManager.VerifyRecord(record); + _table!._recordManager.VerifyRecord(record); Debug.Assert(null != _storage, "null storage"); return _storage.Get(record); } @@ -1130,7 +1139,7 @@ namespace System.Data { try { - _table._recordManager.VerifyRecord(record); + _table!._recordManager.VerifyRecord(record); Debug.Assert(null != _storage, "no storage"); Debug.Assert(null != value, "setting null, expecting dbnull"); _storage.Set(record, value); @@ -1181,7 +1190,7 @@ namespace System.Data catch (Exception e) { ExceptionBuilder.TraceExceptionForCapture(e); - throw ExceptionBuilder.SetFailed(value, this, DataType, e); + throw ExceptionBuilder.SetFailed(value!, this, DataType, e); } DataRow dr = GetDataRow(record); @@ -1217,7 +1226,7 @@ namespace System.Data throw ExceptionBuilder.UniqueAndExpression(); } - UniqueConstraint oldConstraint = null; + UniqueConstraint? oldConstraint = null; if (_table != null) { if (value) @@ -1226,9 +1235,9 @@ namespace System.Data } else { - for (IEnumerator e = Table.Constraints.GetEnumerator(); e.MoveNext();) + for (IEnumerator e = _table.Constraints.GetEnumerator(); e.MoveNext();) { - UniqueConstraint o = (e.Current as UniqueConstraint); + UniqueConstraint? o = (e.Current as UniqueConstraint); if ((null != o) && (o.ColumnsReference.Length == 1) && (o.ColumnsReference[0] == this)) oldConstraint = o; } @@ -1252,7 +1261,7 @@ namespace System.Data } else { - _table.Constraints.Remove(oldConstraint); + _table.Constraints.Remove(oldConstraint!); } } } @@ -1267,9 +1276,9 @@ namespace System.Data internal void InternalUnique(bool value) => _unique = value; - internal string XmlDataType { get; set; } = string.Empty; // The type specified in dt:type attribute + internal string? XmlDataType { get; set; } = string.Empty; // The type specified in dt:type attribute - internal SimpleType SimpleType + internal SimpleType? SimpleType { get { return _simpleType; } set @@ -1279,7 +1288,7 @@ namespace System.Data // there is a change, since we are supporting hierarchy(bacause of Names Simple Type) old check (just one leel base check) is wrong if (value != null && value.CanHaveMaxLength()) { - _maxLength = _simpleType.MaxLength; // this is temp solution, since we dont let simple content to have + _maxLength = value.MaxLength; // this is temp solution, since we dont let simple content to have } //maxlength set but for simple type we want to set it, after coming to decision about it , we should @@ -1354,11 +1363,11 @@ namespace System.Data } } - internal event PropertyChangedEventHandler PropertyChanging; + internal event PropertyChangedEventHandler? PropertyChanging; internal void CheckColumnConstraint(DataRow row, DataRowAction action) { - if (_table.UpdatingCurrent(row, action)) + if (_table!.UpdatingCurrent(row, action)) { CheckNullable(row); CheckMaxLength(row); @@ -1415,7 +1424,7 @@ namespace System.Data else { // since we do not have index, we so sequential search - foreach (DataRow dr in _table.Rows) + foreach (DataRow dr in _table!.Rows) { if (dr.RowState == DataRowState.Deleted) { @@ -1477,7 +1486,7 @@ namespace System.Data if (valuesMatch == 0) { Type leftType = value.GetType(); - Type rightType = _storage.Get(record1).GetType(); + Type rightType = _storage!.Get(record1).GetType(); // if strings, then do exact character by character check if (leftType == typeof(string) && rightType == typeof(string)) { @@ -1493,13 +1502,13 @@ namespace System.Data return false; } - internal int CompareValueTo(int record1, object value) + internal int CompareValueTo(int record1, object? value) { Debug.Assert(null != _storage, "null storage"); return _storage.CompareValueTo(record1, value); } - internal object ConvertValue(object value) + internal object? ConvertValue(object? value) { Debug.Assert(null != _storage, "null storage"); return _storage.ConvertValue(value); @@ -1515,7 +1524,7 @@ namespace System.Data [MethodImpl(MethodImplOptions.NoInlining)] internal DataColumn Clone() { - DataColumn clone = (DataColumn)Activator.CreateInstance(GetType()); + DataColumn clone = (DataColumn)Activator.CreateInstance(GetType())!; clone.SimpleType = SimpleType; @@ -1554,9 +1563,9 @@ namespace System.Data /// /// Finds a relation that this column is the sole child of or null. /// - internal DataRelation FindParentRelation() + internal DataRelation? FindParentRelation() { - var parentRelations = new DataRelation[Table.ParentRelations.Count]; + var parentRelations = new DataRelation[Table!.ParentRelations.Count]; Table.ParentRelations.CopyTo(parentRelations, 0); for (int i = 0; i < parentRelations.Length; i++) @@ -1592,7 +1601,7 @@ namespace System.Data { if (AutoIncrement) { - object value = _autoInc.Current; + object value = _autoInc!.Current; _autoInc.MoveAfter(); Debug.Assert(null != _storage, "no storage"); _storage.Set(record, value); @@ -1639,7 +1648,7 @@ namespace System.Data internal bool IsInRelation() { DataKey key; - DataRelationCollection rels = _table.ParentRelations; + DataRelationCollection rels = _table!.ParentRelations; Debug.Assert(rels != null, "Invalid ParentRelations"); for (int i = 0; i < rels.Count; i++) @@ -1674,9 +1683,9 @@ namespace System.Data bool error = false; object value; - string errorText = null; + string? errorText = null; - foreach (DataRow dr in Table.Rows) + foreach (DataRow dr in Table!.Rows) { if (dr.HasVersion(DataRowVersion.Current)) { @@ -1741,18 +1750,19 @@ namespace System.Data OnPropertyChanging(new PropertyChangedEventArgs(name)); } - private void InsureStorage() + private DataStorage InsureStorage() { if (_storage == null) { _storage = DataStorage.CreateStorage(this, _dataType, _storageType); } + + return _storage; } internal void SetCapacity(int capacity) { - InsureStorage(); - _storage.SetCapacity(capacity); + InsureStorage().SetCapacity(capacity); } private bool ShouldSerializeDefaultValue() => !DefaultValueIsNull; @@ -1767,35 +1777,30 @@ namespace System.Data internal object ConvertXmlToObject(string s) { Debug.Assert(s != null, "Caller is resposible for missing element/attribute case"); - InsureStorage(); - return _storage.ConvertXmlToObject(s); + return InsureStorage().ConvertXmlToObject(s); } internal object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) { - InsureStorage(); - return _storage.ConvertXmlToObject(xmlReader, xmlAttrib); + return InsureStorage().ConvertXmlToObject(xmlReader, xmlAttrib); } internal string ConvertObjectToXml(object value) { Debug.Assert(value != null && (value != DBNull.Value), "Caller is resposible for checking on DBNull"); - InsureStorage(); - return _storage.ConvertObjectToXml(value); + return InsureStorage().ConvertObjectToXml(value); } - internal void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) + internal void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib) { Debug.Assert(value != null && (value != DBNull.Value), "Caller is resposible for checking on DBNull"); - InsureStorage(); - _storage.ConvertObjectToXml(value, xmlWriter, xmlAttrib); + InsureStorage().ConvertObjectToXml(value, xmlWriter, xmlAttrib); } internal object GetEmptyColumnStore(int recordCount) { - InsureStorage(); - return _storage.GetEmptyStorageInternal(recordCount); + return InsureStorage().GetEmptyStorageInternal(recordCount); } internal void CopyValueIntoStore(int record, object store, BitArray nullbits, int storeIndex) @@ -1806,8 +1811,7 @@ namespace System.Data internal void SetStorage(object store, BitArray nullbits) { - InsureStorage(); - _storage.SetStorageInternal(store, nullbits); + InsureStorage().SetStorageInternal(store, nullbits); } internal void AddDependentColumn(DataColumn expressionColumn) @@ -1819,7 +1823,7 @@ namespace System.Data Debug.Assert(!_dependentColumns.Contains(expressionColumn), "duplicate column - expected to be unique"); _dependentColumns.Add(expressionColumn); - _table.AddDependentColumn(expressionColumn); + _table!.AddDependentColumn(expressionColumn); } internal void RemoveDependentColumn(DataColumn expressionColumn) @@ -1828,11 +1832,12 @@ namespace System.Data { _dependentColumns.Remove(expressionColumn); } - _table.RemoveDependentColumn(expressionColumn); + _table!.RemoveDependentColumn(expressionColumn); } - internal void HandleDependentColumnList(DataExpression oldExpression, DataExpression newExpression) + internal void HandleDependentColumnList(DataExpression? oldExpression, DataExpression? newExpression) { + Debug.Assert(_table != null); DataColumn[] dependency; // remove this column from the dependentColumn list of the columns this column depends on. diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnChangeEvent.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnChangeEvent.cs index d5bf9ca..fd94fb3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnChangeEvent.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnChangeEvent.cs @@ -5,7 +5,7 @@ namespace System.Data { public class DataColumnChangeEventArgs : EventArgs { - private DataColumn _column; + private DataColumn? _column; internal DataColumnChangeEventArgs(DataRow row) { @@ -15,7 +15,7 @@ namespace System.Data /// /// Initializes a new instance of the class. /// - public DataColumnChangeEventArgs(DataRow row, DataColumn column, object value) + public DataColumnChangeEventArgs(DataRow row, DataColumn? column, object? value) { Row = row; _column = column; @@ -25,7 +25,7 @@ namespace System.Data /// /// Gets the column whose value is changing. /// - public DataColumn Column => _column; + public DataColumn? Column => _column; /// /// Gets the row whose value is changing. @@ -35,7 +35,7 @@ namespace System.Data /// /// Gets or sets the proposed value. /// - public object ProposedValue { get; set; } + public object? ProposedValue { get; set; } internal void InitializeColumnChangeEvent(DataColumn column, object value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs index b428777..b02be7b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -19,9 +20,9 @@ namespace System.Data private readonly DataTable _table; private readonly ArrayList _list = new ArrayList(); private int _defaultNameIndex = 1; - private DataColumn[] _delayedAddRangeColumns; + private DataColumn?[]? _delayedAddRangeColumns; - private readonly Dictionary _columnFromName; // Links names to columns + private readonly Dictionary _columnFromName; // Links names to columns private bool _fInClear; @@ -35,7 +36,7 @@ namespace System.Data internal DataColumnCollection(DataTable table) { _table = table; - _columnFromName = new Dictionary(); + _columnFromName = new Dictionary(); } /// @@ -60,7 +61,7 @@ namespace System.Data try { // Perf: use the readonly _list field directly and let ArrayList check the range - return (DataColumn)_list[index]; + return (DataColumn)_list[index]!; } catch (ArgumentOutOfRangeException) { @@ -72,7 +73,7 @@ namespace System.Data /// /// Gets the from the collection with the specified name. /// - public DataColumn this[string name] + public DataColumn? this[string name] { get { @@ -81,14 +82,14 @@ namespace System.Data throw ExceptionBuilder.ArgumentNull(nameof(name)); } - DataColumn column; + DataColumn? column; if ((!_columnFromName.TryGetValue(name, out column)) || (column == null)) { // Case-Insensitive compares int index = IndexOfCaseInsensitive(name); if (0 <= index) { - column = (DataColumn)_list[index]; + column = (DataColumn)_list[index]!; } else if (-2 == index) { @@ -100,11 +101,11 @@ namespace System.Data } } - internal DataColumn this[string name, string ns] + internal DataColumn? this[string name, string ns] { get { - DataColumn column; + DataColumn? column; if ((_columnFromName.TryGetValue(name, out column)) && (column != null) && (column.Namespace == ns)) { return column; @@ -208,7 +209,7 @@ namespace System.Data /// Creates and adds a /// with the specified name, type, and compute expression to the columns collection. /// - public DataColumn Add(string columnName, Type type, string expression) + public DataColumn Add(string? columnName, Type type, string expression) { var column = new DataColumn(columnName, type, expression); Add(column); @@ -220,7 +221,7 @@ namespace System.Data /// with the /// specified name and type to the columns collection. /// - public DataColumn Add(string columnName, Type type) + public DataColumn Add(string? columnName, Type type) { var column = new DataColumn(columnName, type); Add(column); @@ -231,7 +232,7 @@ namespace System.Data /// Creates and adds a /// with the specified name to the columns collection. /// - public DataColumn Add(string columnName) + public DataColumn Add(string? columnName) { var column = new DataColumn(columnName); Add(column); @@ -252,10 +253,10 @@ namespace System.Data /// /// Occurs when the columns collection changes, either by adding or removing a column. /// - public event CollectionChangeEventHandler CollectionChanged; + public event CollectionChangeEventHandler? CollectionChanged; - internal event CollectionChangeEventHandler CollectionChanging; - internal event CollectionChangeEventHandler ColumnPropertyChanged; + internal event CollectionChangeEventHandler? CollectionChanging; + internal event CollectionChangeEventHandler? ColumnPropertyChanged; /// /// Adds the column to the columns array. @@ -281,7 +282,7 @@ namespace System.Data int count = _list.Count; for (int i = 0; i < count; i++) { - ((DataColumn)_list[i]).SetOrdinalInternal(i); + ((DataColumn)_list[i]!).SetOrdinalInternal(i); } if (column.ImplementsIChangeTracking) @@ -312,7 +313,7 @@ namespace System.Data /// A DuplicateNameException is thrown if this collection already has a column with the same /// name (case insensitive). /// - private void BaseAdd(DataColumn column) + private void BaseAdd([NotNull] DataColumn? column) { if (column == null) { @@ -338,7 +339,7 @@ namespace System.Data column.SetTable(_table); if (!_table.fInitInProgress && column.Computed) { - if (column.DataExpression.DependsOn(column)) + if (column.DataExpression!.DependsOn(column)) { throw ExceptionBuilder.ExpressionCircular(); } @@ -443,9 +444,9 @@ namespace System.Data /// /// Checks if a given column can be removed from the collection. /// - public bool CanRemove(DataColumn column) => CanRemove(column, false); + public bool CanRemove(DataColumn? column) => CanRemove(column, false); - internal bool CanRemove(DataColumn column, bool fThrowException) + internal bool CanRemove(DataColumn? column, bool fThrowException) { if (column == null) { @@ -515,7 +516,7 @@ namespace System.Data if (!fThrowException) return false; else - throw ExceptionBuilder.CannotRemoveConstraint(_table.Constraints[i].ConstraintName, _table.Constraints[i].Table.TableName); + throw ExceptionBuilder.CannotRemoveConstraint(_table.Constraints[i].ConstraintName, _table.Constraints[i].Table!.TableName); } if (_table.DataSet != null) @@ -527,7 +528,7 @@ namespace System.Data if (!fThrowException) return false; else - throw ExceptionBuilder.CannotRemoveConstraint(constraint.ConstraintName, constraint.Table.TableName); + throw ExceptionBuilder.CannotRemoveConstraint(constraint.ConstraintName, constraint.Table!.TableName); } } @@ -547,7 +548,7 @@ namespace System.Data } Debug.Assert(col.Computed, "invalid (non an expression) column in the expression dependent columns"); - DataExpression expr = col.DataExpression; + DataExpression? expr = col.DataExpression; if ((expr != null) && (expr.DependsOn(column))) { if (!fThrowException) @@ -603,14 +604,14 @@ namespace System.Data { // this will smartly add and remove the appropriate tables. _fInClear = true; - BaseGroupSwitch(columns, oldLength, null, 0); + BaseGroupSwitch(columns, oldLength, Array.Empty(), 0); _fInClear = false; } catch (Exception e) when (ADP.IsCatchableOrSecurityExceptionType(e)) { // something messed up: restore to old values and throw _fInClear = false; - BaseGroupSwitch(null, 0, columns, oldLength); + BaseGroupSwitch(Array.Empty(), 0, columns, oldLength); _list.Clear(); for (int i = 0; i < oldLength; i++) { @@ -629,7 +630,7 @@ namespace System.Data /// public bool Contains(string name) { - DataColumn column; + DataColumn? column; if ((_columnFromName.TryGetValue(name, out column)) && (column != null)) { return true; @@ -640,7 +641,7 @@ namespace System.Data internal bool Contains(string name, bool caseSensitive) { - DataColumn column; + DataColumn? column; if ((_columnFromName.TryGetValue(name, out column)) && (column != null)) { return true; @@ -667,19 +668,19 @@ namespace System.Data for (int i = 0; i < _list.Count; ++i) { - array[index + i] = (DataColumn)_list[i]; + array[index + i] = (DataColumn)_list[i]!; } } /// /// Returns the index of a specified . /// - public int IndexOf(DataColumn column) + public int IndexOf(DataColumn? column) { int columnCount = _list.Count; for (int i = 0; i < columnCount; ++i) { - if (column == (DataColumn)_list[i]) + if (column == (DataColumn)_list[i]!) { return i; } @@ -690,12 +691,12 @@ namespace System.Data /// /// Returns the index of a column specified by name. /// - public int IndexOf(string columnName) + public int IndexOf(string? columnName) { if ((null != columnName) && (0 < columnName.Length)) { int count = Count; - DataColumn column; + DataColumn? column; if ((_columnFromName.TryGetValue(columnName, out column)) && (column != null)) { for (int j = 0; j < count; j++) @@ -719,10 +720,10 @@ namespace System.Data { int hashcode = _table.GetSpecialHashCode(name); int cachedI = -1; - DataColumn column = null; + DataColumn? column = null; for (int i = 0; i < Count; i++) { - column = (DataColumn)_list[i]; + column = (DataColumn)_list[i]!; if ((hashcode == 0 || column._hashCode == 0 || column._hashCode == hashcode) && NamesEqual(column.ColumnName, name, false, _table.Locale) != 0) { @@ -743,7 +744,7 @@ namespace System.Data { if (_delayedAddRangeColumns != null) { - foreach (DataColumn column in _delayedAddRangeColumns) + foreach (DataColumn? column in _delayedAddRangeColumns) { if (column != null) { @@ -751,7 +752,7 @@ namespace System.Data } } - foreach (DataColumn column in _delayedAddRangeColumns) + foreach (DataColumn? column in _delayedAddRangeColumns) { if (column != null) { @@ -787,7 +788,7 @@ namespace System.Data int count = _list.Count; for (int i = 0; i < count; i++) { - ((DataColumn)_list[i]).SetOrdinalInternal(i); + ((DataColumn)_list[i]!).SetOrdinalInternal(i); } CheckIChangeTracking(column); @@ -821,7 +822,7 @@ namespace System.Data /// if the name is equivalent to the next default name to hand out, we increment our defaultNameIndex. /// NOTE: To add a child table, pass column as null /// - internal void RegisterColumnName(string name, DataColumn column) + internal void RegisterColumnName(string name, DataColumn? column) { Debug.Assert(name != null); @@ -902,7 +903,7 @@ namespace System.Data /// public void Remove(string name) { - DataColumn dc = this[name]; + DataColumn? dc = this[name]; if (dc == null) { throw ExceptionBuilder.ColumnNotInTheTable(name, _table.TableName); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs index d63385f..d88eb8c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs @@ -78,7 +78,7 @@ namespace System.Data dataRowView.SetColumnValue(Column, DBNull.Value); // no need to ccheck for the col type and set Sql...Null! } - public override void SetValue(object component, object value) + public override void SetValue(object component, object? value) { DataRowView dataRowView = (DataRowView)component; dataRowView.SetColumnValue(Column, value); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataError.cs b/src/libraries/System.Data.Common/src/System/Data/DataError.cs index a5bb056..3ef950a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataError.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataError.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -14,7 +15,7 @@ namespace System.Data // column-level errors private int _count; - private ColumnError[] _errorList; + private ColumnError[]? _errorList; internal const int initialCapacity = 1; internal DataError() { } @@ -24,6 +25,7 @@ namespace System.Data SetText(rowError); } + [AllowNull] internal string Text { get { return _rowError; } @@ -33,7 +35,7 @@ namespace System.Data internal bool HasErrors => _rowError.Length != 0 || _count != 0; // this method resets the error to the new value. - internal void SetColumnError(DataColumn column, string error) + internal void SetColumnError(DataColumn column, string? error) { Debug.Assert(column != null, "Invalid (null) argument"); Debug.Assert(column.Table != null, "Invalid (loose) column"); @@ -63,7 +65,7 @@ namespace System.Data { for (int i = 0; i < _count; i++) { - if (_errorList[i]._column == column) + if (_errorList![i]._column == column) { return _errorList[i]._error; } @@ -81,7 +83,7 @@ namespace System.Data for (int i = 0; i < _count; i++) { - if (_errorList[i]._column == column) + if (_errorList![i]._column == column) { Array.Copy(_errorList, i + 1, _errorList, i, _count - i - 1); _count--; @@ -95,7 +97,7 @@ namespace System.Data { for (int i = 0; i < _count; i++) { - _errorList[i]._column._errors--; + _errorList![i]._column._errors--; Debug.Assert(_errorList[i]._column._errors >= 0, "missing error counts"); } _count = 0; @@ -108,7 +110,7 @@ namespace System.Data for (int i = 0; i < _count; i++) { - cols[i] = _errorList[i]._column; + cols[i] = _errorList![i]._column; } return cols; @@ -117,7 +119,7 @@ namespace System.Data /// /// Sets the error message for the . /// - private void SetText(string errorText) + private void SetText(string? errorText) { if (null == errorText) { @@ -131,15 +133,15 @@ namespace System.Data // try to find the column for (int i = 0; i < _count; i++) { - if (_errorList[i]._column == column) + if (_errorList![i]._column == column) { return i; } } - if (_count >= _errorList.Length) + if (_count >= _errorList!.Length) { - int newCapacity = Math.Min(_count * 2, column.Table.Columns.Count); + int newCapacity = Math.Min(_count * 2, column.Table!.Columns.Count); var biggerList = new ColumnError[newCapacity]; Array.Copy(_errorList, biggerList, _count); _errorList = biggerList; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataException.cs b/src/libraries/System.Data.Common/src/System/Data/DataException.cs index 3122615..261005c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataException.cs @@ -21,12 +21,12 @@ namespace System.Data HResult = HResults.Data; } - public DataException(string s) : base(s) + public DataException(string? s) : base(s) { HResult = HResults.Data; } - public DataException(string s, Exception innerException) : base(s, innerException) { } + public DataException(string? s, Exception? innerException) : base(s, innerException) { } }; [Serializable] @@ -42,12 +42,12 @@ namespace System.Data HResult = HResults.DataConstraint; } - public ConstraintException(string s) : base(s) + public ConstraintException(string? s) : base(s) { HResult = HResults.DataConstraint; } - public ConstraintException(string message, Exception innerException) : base(message, innerException) + public ConstraintException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataConstraint; } @@ -72,12 +72,12 @@ namespace System.Data /// /// Initializes a new instance of the class with the specified string. /// - public DeletedRowInaccessibleException(string s) : base(s) + public DeletedRowInaccessibleException(string? s) : base(s) { HResult = HResults.DataDeletedRowInaccessible; } - public DeletedRowInaccessibleException(string message, Exception innerException) : base(message, innerException) + public DeletedRowInaccessibleException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataDeletedRowInaccessible; } @@ -96,12 +96,12 @@ namespace System.Data HResult = HResults.DataDuplicateName; } - public DuplicateNameException(string s) : base(s) + public DuplicateNameException(string? s) : base(s) { HResult = HResults.DataDuplicateName; } - public DuplicateNameException(string message, Exception innerException) : base(message, innerException) + public DuplicateNameException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataDuplicateName; } @@ -120,12 +120,12 @@ namespace System.Data HResult = HResults.DataInRowChangingEvent; } - public InRowChangingEventException(string s) : base(s) + public InRowChangingEventException(string? s) : base(s) { HResult = HResults.DataInRowChangingEvent; } - public InRowChangingEventException(string message, Exception innerException) : base(message, innerException) + public InRowChangingEventException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataInRowChangingEvent; } @@ -144,12 +144,12 @@ namespace System.Data HResult = HResults.DataInvalidConstraint; } - public InvalidConstraintException(string s) : base(s) + public InvalidConstraintException(string? s) : base(s) { HResult = HResults.DataInvalidConstraint; } - public InvalidConstraintException(string message, Exception innerException) : base(message, innerException) + public InvalidConstraintException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataInvalidConstraint; } @@ -168,12 +168,12 @@ namespace System.Data HResult = HResults.DataMissingPrimaryKey; } - public MissingPrimaryKeyException(string s) : base(s) + public MissingPrimaryKeyException(string? s) : base(s) { HResult = HResults.DataMissingPrimaryKey; } - public MissingPrimaryKeyException(string message, Exception innerException) : base(message, innerException) + public MissingPrimaryKeyException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataMissingPrimaryKey; } @@ -192,12 +192,12 @@ namespace System.Data HResult = HResults.DataNoNullAllowed; } - public NoNullAllowedException(string s) : base(s) + public NoNullAllowedException(string? s) : base(s) { HResult = HResults.DataNoNullAllowed; } - public NoNullAllowedException(string message, Exception innerException) : base(message, innerException) + public NoNullAllowedException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataNoNullAllowed; } @@ -216,12 +216,12 @@ namespace System.Data HResult = HResults.DataReadOnly; } - public ReadOnlyException(string s) : base(s) + public ReadOnlyException(string? s) : base(s) { HResult = HResults.DataReadOnly; } - public ReadOnlyException(string message, Exception innerException) : base(message, innerException) + public ReadOnlyException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataReadOnly; } @@ -240,12 +240,12 @@ namespace System.Data HResult = HResults.DataRowNotInTable; } - public RowNotInTableException(string s) : base(s) + public RowNotInTableException(string? s) : base(s) { HResult = HResults.DataRowNotInTable; } - public RowNotInTableException(string message, Exception innerException) : base(message, innerException) + public RowNotInTableException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataRowNotInTable; } @@ -264,12 +264,12 @@ namespace System.Data HResult = HResults.DataVersionNotFound; } - public VersionNotFoundException(string s) : base(s) + public VersionNotFoundException(string? s) : base(s) { HResult = HResults.DataVersionNotFound; } - public VersionNotFoundException(string message, Exception innerException) : base(message, innerException) + public VersionNotFoundException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.DataVersionNotFound; } @@ -315,19 +315,20 @@ namespace System.Data internal static Exception _Argument(string error) => TraceExceptionAsReturnValue(new ArgumentException(error)); internal static Exception _Argument(string paramName, string error) => TraceExceptionAsReturnValue(new ArgumentException(error)); - internal static Exception _Argument(string error, Exception innerException) => TraceExceptionAsReturnValue(new ArgumentException(error, innerException)); + internal static Exception _Argument(string error, Exception? innerException) => TraceExceptionAsReturnValue(new ArgumentException(error, innerException)); private static Exception _ArgumentNull(string paramName, string msg) => TraceExceptionAsReturnValue(new ArgumentNullException(paramName, msg)); internal static Exception _ArgumentOutOfRange(string paramName, string msg) => TraceExceptionAsReturnValue(new ArgumentOutOfRangeException(paramName, msg)); private static Exception _IndexOutOfRange(string error) => TraceExceptionAsReturnValue(new IndexOutOfRangeException(error)); private static Exception _InvalidOperation(string error) => TraceExceptionAsReturnValue(new InvalidOperationException(error)); private static Exception _InvalidEnumArgumentException(string error) => TraceExceptionAsReturnValue(new InvalidEnumArgumentException(error)); - private static Exception _InvalidEnumArgumentException(T value) => _InvalidEnumArgumentException(SR.Format(SR.ADP_InvalidEnumerationValue, typeof(T).Name, value.ToString())); + private static Exception _InvalidEnumArgumentException(T value) where T : Enum + => _InvalidEnumArgumentException(SR.Format(SR.ADP_InvalidEnumerationValue, typeof(T).Name, value.ToString())); // // System.Data exceptions // - private static void ThrowDataException(string error, Exception innerException) + private static void ThrowDataException(string error, Exception? innerException) { throw TraceExceptionAsReturnValue(new DataException(error, innerException)); } @@ -466,7 +467,7 @@ namespace System.Data public static Exception ReadOnlyAndExpression() => _ReadOnly(SR.DataColumn_ReadOnlyAndExpression); public static Exception ReadOnly(string column) => _ReadOnly(SR.Format(SR.DataColumn_ReadOnly, column)); public static Exception UniqueAndExpression() => _Argument(SR.DataColumn_UniqueAndExpression); - public static Exception SetFailed(object value, DataColumn column, Type type, Exception innerException) => _Argument(innerException.Message + SR.Format(SR.DataColumn_SetFailed, value.ToString(), column.ColumnName, type.Name), innerException); + public static Exception SetFailed(object? value, DataColumn column, Type type, Exception innerException) => _Argument(innerException.Message + SR.Format(SR.DataColumn_SetFailed, value?.ToString(), column.ColumnName, type.Name), innerException); public static Exception CannotSetToNull(DataColumn column) => _Argument(SR.Format(SR.DataColumn_CannotSetToNull, column.ColumnName)); public static Exception LongerThanMaxLength(DataColumn column) => _Argument(SR.Format(SR.DataColumn_LongerThanMaxLength, column.ColumnName)); public static Exception CannotSetMaxLength(DataColumn column, int value) => _Argument(SR.Format(SR.DataColumn_CannotSetMaxLength, column.ColumnName, value.ToString(CultureInfo.InvariantCulture))); @@ -609,7 +610,7 @@ namespace System.Data public static Exception EnforceConstraint() => _Constraint(SR.Data_EnforceConstraints); public static Exception CaseLocaleMismatch() => _Argument(SR.DataRelation_CaseLocaleMismatch); public static Exception CannotChangeCaseLocale() => CannotChangeCaseLocale(null); - public static Exception CannotChangeCaseLocale(Exception innerException) => _Argument(SR.DataSet_CannotChangeCaseLocale, innerException); + public static Exception CannotChangeCaseLocale(Exception? innerException) => _Argument(SR.DataSet_CannotChangeCaseLocale, innerException); public static Exception CannotChangeSchemaSerializationMode() => _InvalidOperation(SR.DataSet_CannotChangeSchemaSerializationMode); public static Exception InvalidSchemaSerializationMode(Type enumType, string mode) => _InvalidEnumArgumentException(SR.Format(SR.ADP_InvalidEnumerationValue, enumType.Name, mode)); public static Exception InvalidRemotingFormat(SerializationFormat mode) => _InvalidEnumArgumentException(mode); @@ -689,7 +690,7 @@ namespace System.Data public static Exception DataTableInferenceNotSupported() => _InvalidOperation(SR.Xml_DataTableInferenceNotSupported); /// throw DataException for multitarget failure - internal static void ThrowMultipleTargetConverter(Exception innerException) + internal static void ThrowMultipleTargetConverter(Exception? innerException) { string res = (null != innerException) ? SR.Xml_MultipleTargetConverterError : SR.Xml_MultipleTargetConverterEmpty; ThrowDataException(res, innerException); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataKey.cs b/src/libraries/System.Data.Common/src/System/Data/DataKey.cs index b447f6a..df6edda 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataKey.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataKey.cs @@ -66,10 +66,10 @@ namespace System.Data internal DataColumn[] ColumnsReference => _columns; internal bool HasValue => null != _columns; - internal DataTable Table => _columns[0].Table; + internal DataTable Table => _columns[0].Table!; internal void CheckState() { - DataTable table = _columns[0].Table; + DataTable? table = _columns[0].Table; if (table == null) { @@ -148,7 +148,7 @@ namespace System.Data return base.GetHashCode(); } - public override bool Equals(object value) + public override bool Equals(object? value) { Debug.Fail("need to directly call Equals(DataKey)"); return Equals((DataKey)value); @@ -220,7 +220,7 @@ namespace System.Data internal Index GetSortIndex(DataViewRowState recordStates) { IndexField[] indexDesc = GetIndexDesc(); - return _columns[0].Table.GetIndex(indexDesc, recordStates, null); + return _columns[0].Table!.GetIndex(indexDesc, recordStates, null); } internal bool RecordsEqual(int record1, int record2) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs index 4372984..ac3e4c3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using System.Data.Common; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -170,7 +171,7 @@ namespace System.Data return reader.IsDBNullAsync(reader.GetOrdinal(name), cancellationToken); } - private static void AssertNotNull(DbDataReader reader) + private static void AssertNotNull([NotNull] DbDataReader? reader) { if (reader is null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs index f7ce481..c53fa2a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs @@ -24,6 +24,7 @@ using System.Diagnostics; using System.Globalization; using System.Data.Common; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Data @@ -33,23 +34,23 @@ namespace System.Data public class DataRelation { // properties - private DataSet _dataSet; - internal PropertyCollection _extendedProperties; + private DataSet? _dataSet; + internal PropertyCollection? _extendedProperties; internal string _relationName = string.Empty; // state private DataKey _childKey; private DataKey _parentKey; - private UniqueConstraint _parentKeyConstraint; - private ForeignKeyConstraint _childKeyConstraint; + private UniqueConstraint? _parentKeyConstraint; + private ForeignKeyConstraint? _childKeyConstraint; // Design time serialization - internal string[] _parentColumnNames; - internal string[] _childColumnNames; - internal string _parentTableName; - internal string _childTableName; - internal string _parentTableNamespace; - internal string _childTableNamespace; + internal string[]? _parentColumnNames; + internal string[]? _childColumnNames; + internal string? _parentTableName; + internal string? _childTableName; + internal string? _parentTableNamespace; + internal string? _childTableNamespace; /// /// This stores whether the child element appears beneath the parent in the XML persisted files. @@ -71,7 +72,7 @@ namespace System.Data /// Initializes a new instance of the class using the specified name, /// parent, and child columns. /// - public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn) : + public DataRelation(string? relationName, DataColumn parentColumn, DataColumn childColumn) : this(relationName, parentColumn, childColumn, true) { } @@ -80,16 +81,16 @@ namespace System.Data /// Initializes a new instance of the class using the specified name, parent, and child columns, and /// value to create constraints. /// - public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) + public DataRelation(string? relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) { DataCommonEventSource.Log.Trace(" {0}, relationName='{1}', parentColumn={2}, childColumn={3}, createConstraints={4}", ObjectID, relationName, (parentColumn != null) ? parentColumn.ObjectID : 0, (childColumn != null) ? childColumn.ObjectID : 0, createConstraints); DataColumn[] parentColumns = new DataColumn[1]; - parentColumns[0] = parentColumn; + parentColumns[0] = parentColumn!; DataColumn[] childColumns = new DataColumn[1]; - childColumns[0] = childColumn; + childColumns[0] = childColumn!; Create(relationName, parentColumns, childColumns, createConstraints); } @@ -97,7 +98,7 @@ namespace System.Data /// Initializes a new instance of the class using the specified name /// and matched arrays of parent and child columns. /// - public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns) : + public DataRelation(string? relationName, DataColumn[] parentColumns, DataColumn[] childColumns) : this(relationName, parentColumns, childColumns, true) { } @@ -106,13 +107,13 @@ namespace System.Data /// Initializes a new instance of the class using the specified name, matched arrays of parent /// and child columns, and value to create constraints. /// - public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) + public DataRelation(string? relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) { Create(relationName, parentColumns, childColumns, createConstraints); } [Browsable(false)] // design-time ctor - public DataRelation(string relationName, string parentTableName, string childTableName, string[] parentColumnNames, string[] childColumnNames, bool nested) + public DataRelation(string relationName, string? parentTableName, string? childTableName, string[]? parentColumnNames, string[]? childColumnNames, bool nested) { _relationName = relationName; _parentColumnNames = parentColumnNames; @@ -123,7 +124,7 @@ namespace System.Data } [Browsable(false)] // design-time ctor - public DataRelation(string relationName, string parentTableName, string parentTableNamespace, string childTableName, string childTableNamespace, string[] parentColumnNames, string[] childColumnNames, bool nested) + public DataRelation(string relationName, string? parentTableName, string? parentTableNamespace, string? childTableName, string? childTableNamespace, string[]? parentColumnNames, string[]? childColumnNames, bool nested) { _relationName = relationName; _parentColumnNames = parentColumnNames; @@ -184,7 +185,7 @@ namespace System.Data /// Gets the to which the relations' collection belongs to. /// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)] - public virtual DataSet DataSet + public virtual DataSet? DataSet { get { @@ -240,7 +241,7 @@ namespace System.Data return index.GetRows(values); } - internal static DataRow GetParentRow(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version) + internal static DataRow? GetParentRow(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version) { if (!childRow.HasVersion((version == DataRowVersion.Original) ? DataRowVersion.Original : DataRowVersion.Current)) { @@ -275,7 +276,7 @@ namespace System.Data /// /// Internally sets the DataSet pointer. /// - internal void SetDataSet(DataSet dataSet) + internal void SetDataSet(DataSet? dataSet) { if (_dataSet != dataSet) { @@ -343,6 +344,7 @@ namespace System.Data /// data set's . /// [DefaultValue("")] + [AllowNull] public virtual string RelationName { get @@ -419,7 +421,7 @@ namespace System.Data if (ChildTable == ParentTable) { - if (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0) + if (string.Compare(ChildTable.TableName, ChildTable.DataSet!.DataSetName, true, ChildTable.DataSet.Locale) == 0) throw ExceptionBuilder.SelfnestedDatasetConflictingName(ChildTable.TableName); return; //allow self join tables. } @@ -482,7 +484,7 @@ namespace System.Data CheckNamespaceValidityForNestedRelations(ParentTable.Namespace); } Debug.Assert(ChildTable != null, "On a DataSet, but not on Table. Bad state"); - ForeignKeyConstraint constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference); + ForeignKeyConstraint? constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference); if (constraint != null) { constraint.CheckConstraint(); @@ -518,7 +520,7 @@ namespace System.Data if (ChildTable.DataSet != null && (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0)) { - throw ExceptionBuilder.DatasetConflictingName(_dataSet.DataSetName); + throw ExceptionBuilder.DatasetConflictingName(DataSet.DataSetName); } ChildTable._fNestedInDataset = false; } @@ -542,9 +544,9 @@ namespace System.Data if (value) { if (string.IsNullOrEmpty(ChildTable.Namespace) && ((ChildTable.NestedParentsCount > 1) || - ((ChildTable.NestedParentsCount > 0) && !(ChildTable.DataSet.Relations.Contains(RelationName))))) + ((ChildTable.NestedParentsCount > 0) && !(ChildTable.DataSet!.Relations.Contains(RelationName))))) { - string parentNs = null; + string? parentNs = null; foreach (DataRelation rel in ChildTable.ParentRelations) { if (rel.Nested) @@ -583,7 +585,7 @@ namespace System.Data /// /// Gets the constraint which ensures values in a column are unique. /// - public virtual UniqueConstraint ParentKeyConstraint + public virtual UniqueConstraint? ParentKeyConstraint { get { @@ -592,7 +594,7 @@ namespace System.Data } } - internal void SetParentKeyConstraint(UniqueConstraint value) + internal void SetParentKeyConstraint(UniqueConstraint? value) { Debug.Assert(_parentKeyConstraint == null || value == null, "ParentKeyConstraint should not have been set already."); _parentKeyConstraint = value; @@ -602,7 +604,7 @@ namespace System.Data /// /// Gets the for the relation. /// - public virtual ForeignKeyConstraint ChildKeyConstraint + public virtual ForeignKeyConstraint? ChildKeyConstraint { get { @@ -623,13 +625,13 @@ namespace System.Data set { _checkMultipleNested = value; } } - internal void SetChildKeyConstraint(ForeignKeyConstraint value) + internal void SetChildKeyConstraint(ForeignKeyConstraint? value) { Debug.Assert(_childKeyConstraint == null || value == null, "ChildKeyConstraint should not have been set already."); _childKeyConstraint = value; } - internal event PropertyChangedEventHandler PropertyChanging; + internal event PropertyChangedEventHandler? PropertyChanging; // If we're not in a dataSet relations collection, we need to verify on every property get that we're // still a good relation object. @@ -680,7 +682,7 @@ namespace System.Data } } - private void Create(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) + private void Create(string? relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, relationName='{1}', createConstraints={2}", ObjectID, relationName, createConstraints); try @@ -695,7 +697,7 @@ namespace System.Data for (int i = 0; i < parentColumns.Length; i++) { - if ((parentColumns[i].Table.DataSet == null) || (childColumns[i].Table.DataSet == null)) + if ((parentColumns[i].Table!.DataSet == null) || (childColumns[i].Table!.DataSet == null)) { throw ExceptionBuilder.ParentOrChildColumnsDoNotHaveDataSet(); } @@ -715,9 +717,10 @@ namespace System.Data internal DataRelation Clone(DataSet destination) { DataCommonEventSource.Log.Trace(" {0}, destination={1}", ObjectID, (destination != null) ? destination.ObjectID : 0); + Debug.Assert(destination != null); - DataTable parent = destination.Tables[ParentTable.TableName, ParentTable.Namespace]; - DataTable child = destination.Tables[ChildTable.TableName, ChildTable.Namespace]; + DataTable parent = destination.Tables[ParentTable.TableName, ParentTable.Namespace]!; + DataTable child = destination.Tables[ChildTable.TableName, ChildTable.Namespace]!; int keyLength = _parentKey.ColumnsReference.Length; DataColumn[] parentColumns = new DataColumn[keyLength]; @@ -725,8 +728,8 @@ namespace System.Data for (int i = 0; i < keyLength; i++) { - parentColumns[i] = parent.Columns[ParentKey.ColumnsReference[i].ColumnName]; - childColumns[i] = child.Columns[ChildKey.ColumnsReference[i].ColumnName]; + parentColumns[i] = parent.Columns[ParentKey.ColumnsReference[i].ColumnName]!; + childColumns[i] = child.Columns[ChildKey.ColumnsReference[i].ColumnName]!; } DataRelation clone = new DataRelation(_relationName, parentColumns, childColumns, false); @@ -823,14 +826,14 @@ namespace System.Data return false; } - string generatedname = col.Table.TableName + "_Id"; + string generatedname = col.Table!.TableName + "_Id"; if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0")) { return true; } - generatedname = ParentColumnsReference[0].Table.TableName + "_Id"; + generatedname = ParentColumnsReference[0].Table!.TableName + "_Id"; if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0")) { return true; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs index 3a164dd..d910255 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs @@ -4,6 +4,7 @@ using System.Collections; using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data @@ -16,12 +17,12 @@ namespace System.Data [DefaultProperty("Table")] public abstract class DataRelationCollection : InternalDataCollectionBase { - private DataRelation _inTransition; + private DataRelation? _inTransition; private int _defaultNameIndex = 1; - private CollectionChangeEventHandler _onCollectionChangedDelegate; - private CollectionChangeEventHandler _onCollectionChangingDelegate; + private CollectionChangeEventHandler? _onCollectionChangedDelegate; + private CollectionChangeEventHandler? _onCollectionChangingDelegate; private static int s_objectTypeCount; // Bid counter private readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); @@ -36,7 +37,7 @@ namespace System.Data /// /// Gets the relation specified by name. /// - public abstract DataRelation this[string name] { get; } + public abstract DataRelation? this[string? name] { get; } /// /// Adds the relation to the collection. @@ -55,7 +56,7 @@ namespace System.Data try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Add, relation)); - AddCore(relation); + AddCore(relation!); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, relation)); } finally @@ -69,7 +70,7 @@ namespace System.Data } } - public virtual void AddRange(DataRelation[] relations) + public virtual void AddRange(DataRelation[]? relations) { if (relations != null) { @@ -88,7 +89,7 @@ namespace System.Data /// specified name, parent columns, /// child columns, and adds it to the collection. /// - public virtual DataRelation Add(string name, DataColumn[] parentColumns, DataColumn[] childColumns) + public virtual DataRelation Add(string? name, DataColumn[] parentColumns, DataColumn[] childColumns) { var relation = new DataRelation(name, parentColumns, childColumns); Add(relation); @@ -103,7 +104,7 @@ namespace System.Data /// An InvalidRelationException is thrown if the relation can't be created based on the parameters. /// The CollectionChanged event is fired if it succeeds. /// - public virtual DataRelation Add(string name, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) + public virtual DataRelation Add(string? name, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) { var relation = new DataRelation(name, parentColumns, childColumns, createConstraints); Add(relation); @@ -133,7 +134,7 @@ namespace System.Data /// An InvalidConstraintException is thrown if the relation can't be created based on the parameters. /// The CollectionChanged event is fired if it succeeds. /// - public virtual DataRelation Add(string name, DataColumn parentColumn, DataColumn childColumn) + public virtual DataRelation Add(string? name, DataColumn parentColumn, DataColumn childColumn) { var relation = new DataRelation(name, parentColumn, childColumn); Add(relation); @@ -149,7 +150,7 @@ namespace System.Data /// An InvalidConstraintException is thrown if the relation can't be created based on the parameters. /// The CollectionChanged event is fired if it succeeds. /// - public virtual DataRelation Add(string name, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) + public virtual DataRelation Add(string? name, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) { var relation = new DataRelation(name, parentColumn, childColumn, createConstraints); Add(relation); @@ -209,7 +210,7 @@ namespace System.Data } } - public event CollectionChangeEventHandler CollectionChanged + public event CollectionChangeEventHandler? CollectionChanged { add { @@ -223,7 +224,7 @@ namespace System.Data } } - internal event CollectionChangeEventHandler CollectionChanging + internal event CollectionChangeEventHandler? CollectionChanging { add { @@ -274,7 +275,7 @@ namespace System.Data /// /// Returns true if this collection has a relation with the given name (case insensitive), false otherwise. /// - public virtual bool Contains(string name) => (InternalIndexOf(name) >= 0); + public virtual bool Contains(string? name) => (InternalIndexOf(name) >= 0); public void CopyTo(DataRelation[] array, int index) { @@ -296,19 +297,19 @@ namespace System.Data for (int i = 0; i < alist.Count; ++i) { - array[index + i] = (DataRelation)alist[i]; + array[index + i] = (DataRelation)alist[i]!; } } /// /// Returns the index of a specified . /// - public virtual int IndexOf(DataRelation relation) + public virtual int IndexOf(DataRelation? relation) { int relationCount = List.Count; for (int i = 0; i < relationCount; ++i) { - if (relation == (DataRelation)List[i]) + if (relation == (DataRelation)List[i]!) { return i; } @@ -321,13 +322,13 @@ namespace System.Data /// relation with the given name (case insensitive), or -1 if the relation /// doesn't exist in the collection. /// - public virtual int IndexOf(string relationName) + public virtual int IndexOf(string? relationName) { int index = InternalIndexOf(relationName); return (index < 0) ? -1 : index; } - internal int InternalIndexOf(string name) + internal int InternalIndexOf(string? name) { int cachedI = -1; if ((null != name) && (0 < name.Length)) @@ -336,7 +337,7 @@ namespace System.Data int result = 0; for (int i = 0; i < count; i++) { - DataRelation relation = (DataRelation)List[i]; + DataRelation relation = (DataRelation)List[i]!; result = NamesEqual(relation.RelationName, name, false, GetDataSet().Locale); if (result == 1) { @@ -414,7 +415,7 @@ namespace System.Data /// /// Verifies if a given relation can be removed from the collection. /// - public virtual bool CanRemove(DataRelation relation) => relation != null && relation.DataSet == GetDataSet(); + public virtual bool CanRemove(DataRelation? relation) => relation != null && relation.DataSet == GetDataSet(); /// /// Removes the given relation from the collection. @@ -434,7 +435,7 @@ namespace System.Data try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Remove, relation)); - RemoveCore(relation); + RemoveCore(relation!); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, relation)); } finally @@ -451,6 +452,7 @@ namespace System.Data public void RemoveAt(int index) { DataRelation dr = this[index]; + // TODO: Not needed, this[] throws if (dr == null) { throw ExceptionBuilder.RelationOutOfRange(index); @@ -465,7 +467,7 @@ namespace System.Data /// public void Remove(string name) { - DataRelation dr = this[name]; + DataRelation? dr = this[name]; if (dr == null) { throw ExceptionBuilder.RelationNotInTheDataSet(name); @@ -546,7 +548,7 @@ namespace System.Data protected override DataSet GetDataSet() { EnsureDataSet(); - return _table.DataSet; + return _table.DataSet!; } public override DataRelation this[int index] @@ -555,26 +557,26 @@ namespace System.Data { if (index >= 0 && index < _relations.Count) { - return (DataRelation)_relations[index]; + return (DataRelation)_relations[index]!; } throw ExceptionBuilder.RelationOutOfRange(index); } } - public override DataRelation this[string name] + public override DataRelation? this[string? name] { get { int index = InternalIndexOf(name); if (index == -2) { - throw ExceptionBuilder.CaseInsensitiveNameConflict(name); + throw ExceptionBuilder.CaseInsensitiveNameConflict(name!); } - return (index < 0) ? null : (DataRelation)List[index]; + return (index < 0) ? null : (DataRelation)List[index]!; } } - internal event CollectionChangeEventHandler RelationPropertyChanged; + internal event CollectionChangeEventHandler? RelationPropertyChanged; internal void OnRelationPropertyChanged(CollectionChangeEventArgs ccevent) { @@ -615,13 +617,15 @@ namespace System.Data AddCache(relation); } - public override bool CanRemove(DataRelation relation) + public override bool CanRemove(DataRelation? relation) { if (!base.CanRemove(relation)) { return false; } + Debug.Assert(relation != null); + if (_fParentCollection) { if (relation.ChildTable != _table) @@ -683,7 +687,7 @@ namespace System.Data { private readonly DataSet _dataSet; private readonly ArrayList _relations; - private DataRelation[] _delayLoadingRelations; + private DataRelation[]? _delayLoadingRelations; internal DataSetRelationCollection(DataSet dataSet) { @@ -697,7 +701,7 @@ namespace System.Data protected override ArrayList List => _relations; - public override void AddRange(DataRelation[] relations) + public override void AddRange(DataRelation[]? relations) { if (_dataSet._fInitInProgress) { @@ -734,22 +738,22 @@ namespace System.Data { if (index >= 0 && index < _relations.Count) { - return (DataRelation)_relations[index]; + return (DataRelation)_relations[index]!; } throw ExceptionBuilder.RelationOutOfRange(index); } } - public override DataRelation this[string name] + public override DataRelation? this[string? name] { get { int index = InternalIndexOf(name); if (index == -2) { - throw ExceptionBuilder.CaseInsensitiveNameConflict(name); + throw ExceptionBuilder.CaseInsensitiveNameConflict(name!); } - return (index < 0) ? null : (DataRelation)List[index]; + return (index < 0) ? null : (DataRelation)List[index]!; } } @@ -780,9 +784,9 @@ namespace System.Data for (int i = 0; i < _relations.Count; i++) { - if (childKey.ColumnsEqual(((DataRelation)_relations[i]).ChildKey)) + if (childKey.ColumnsEqual(((DataRelation)_relations[i]!).ChildKey)) { - if (relation.ParentKey.ColumnsEqual(((DataRelation)_relations[i]).ParentKey)) + if (relation.ParentKey.ColumnsEqual(((DataRelation)_relations[i]!).ParentKey)) throw ExceptionBuilder.RelationAlreadyExists(); } } @@ -798,7 +802,7 @@ namespace System.Data relation.ChildTable.CacheNestedParent(); } - ForeignKeyConstraint foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference); + ForeignKeyConstraint? foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference); if (relation._createConstraints) { if (foreignKey == null) @@ -816,7 +820,7 @@ namespace System.Data } } } - UniqueConstraint key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference); + UniqueConstraint? key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference); relation.SetParentKeyConstraint(key); relation.SetChildKeyConstraint(foreignKey); } @@ -884,20 +888,20 @@ namespace System.Data { if (rel._parentTableNamespace == null) { - parents[j] = _dataSet.Tables[rel._parentTableName].Columns[rel._parentColumnNames[j]]; + parents[j] = _dataSet.Tables[rel._parentTableName!]!.Columns[rel._parentColumnNames[j]]!; } else { - parents[j] = _dataSet.Tables[rel._parentTableName, rel._parentTableNamespace].Columns[rel._parentColumnNames[j]]; + parents[j] = _dataSet.Tables[rel._parentTableName!, rel._parentTableNamespace]!.Columns[rel._parentColumnNames[j]]!; } if (rel._childTableNamespace == null) { - childs[j] = _dataSet.Tables[rel._childTableName].Columns[rel._childColumnNames[j]]; + childs[j] = _dataSet.Tables[rel._childTableName!]!.Columns[rel._childColumnNames[j]]!; } else { - childs[j] = _dataSet.Tables[rel._childTableName, rel._childTableNamespace].Columns[rel._childColumnNames[j]]; + childs[j] = _dataSet.Tables[rel._childTableName!, rel._childTableNamespace]!.Columns[rel._childColumnNames[j]]!; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs index 45c6807..084cbd2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs @@ -4,6 +4,7 @@ using System.Collections; using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Data @@ -27,11 +28,11 @@ namespace System.Data internal bool _inDeletingEvent; internal bool _inCascade; - private DataColumn _lastChangedColumn; // last successfully changed column + private DataColumn? _lastChangedColumn; // last successfully changed column private int _countColumnChange; // number of columns changed during edit mode - private DataError _error; - private object _element; + private DataError? _error; + private object? _element; private int _rbTreeNodeId; // if row is not detached, Id used for computing index in rows collection @@ -49,13 +50,13 @@ namespace System.Data _columns = _table.Columns; } - internal XmlBoundElement Element + internal XmlBoundElement? Element { - get { return (XmlBoundElement)_element; } + get { return (XmlBoundElement?)_element; } set { _element = value; } } - internal DataColumn LastChangedColumn + internal DataColumn? LastChangedColumn { get { @@ -84,6 +85,7 @@ namespace System.Data /// /// Gets or sets the custom error description for a row. /// + [AllowNull] public string RowError { get { return _error == null ? string.Empty : _error.Text; } @@ -207,7 +209,7 @@ namespace System.Data int count = _table.Rows.Count, i = 0; // need to optimize this for count > 100 - DataRow parent = GetParentRow(rel); + DataRow? parent = GetParentRow(rel); while (parent != null) { if ((parent == this) || (i > count)) @@ -233,7 +235,7 @@ namespace System.Data { CheckForLoops(rel); } - DataRow row = GetParentRow(rel); + DataRow? row = GetParentRow(rel); if (row != null) { count++; @@ -247,6 +249,7 @@ namespace System.Data /// /// Gets or sets the data stored in the column specified by name. /// + [AllowNull] public object this[string columnName] { get @@ -267,6 +270,7 @@ namespace System.Data /// /// Gets or sets the data stored in the specified . /// + [AllowNull] public object this[DataColumn column] { get @@ -293,7 +297,7 @@ namespace System.Data // note we intentionally do not try/catch this event. // note: we also allow user to do anything at this point // infinite loops are possible if user calls Item or ItemArray during the event - DataColumnChangeEventArgs e = null; + DataColumnChangeEventArgs? e = null; if (_table.NeedColumnChangeEvents) { e = new DataColumnChangeEventArgs(this, column, value); @@ -311,7 +315,7 @@ namespace System.Data throw ExceptionBuilder.ReadOnly(column.ColumnName); } - object proposed = ((null != e) ? e.ProposedValue : value); + object? proposed = ((null != e) ? e.ProposedValue : value); if (null == proposed) { if (column.IsValueType) @@ -358,6 +362,7 @@ namespace System.Data /// /// Gets the data stored in the column, specified by index and version of the data to retrieve. /// + [AllowNull] public object this[int columnIndex, DataRowVersion version] { get @@ -373,6 +378,7 @@ namespace System.Data /// /// Gets the specified version of data stored in the named column. /// + [AllowNull] public object this[string columnName, DataRowVersion version] { get @@ -388,6 +394,7 @@ namespace System.Data /// /// Gets the specified version of data stored in the specified . /// + [AllowNull] public object this[DataColumn column, DataRowVersion version] { get @@ -403,7 +410,12 @@ namespace System.Data /// /// Gets or sets all of the values for this row through an array. /// - public object[] ItemArray + /// + /// Arrays returned from this property will never contain . + /// When setting this property, indicates that the current column value + /// should be left as-is. can be used to set the the value to null. + /// + public object?[] ItemArray { get { @@ -428,7 +440,7 @@ namespace System.Data { throw ExceptionBuilder.ValueArrayLength(); } - DataColumnChangeEventArgs e = null; + DataColumnChangeEventArgs? e = null; if (_table.NeedColumnChangeEvents) { e = new DataColumnChangeEventArgs(this); @@ -438,7 +450,7 @@ namespace System.Data for (int i = 0; i < value.Length; ++i) { // Empty means don't change the row. - if (null != value[i]) + if (value[i] is { } item) { // may throw exception if user removes column from table during event DataColumn column = _columns[i]; @@ -454,7 +466,7 @@ namespace System.Data // infinite loops are possible if user calls Item or ItemArray during the event if (null != e) { - e.InitializeColumnChangeEvent(column, value[i]); + e.InitializeColumnChangeEvent(column, item); _table.OnColumnChanging(e); } @@ -474,7 +486,7 @@ namespace System.Data BeginEditInternal(); } - object proposed = (null != e) ? e.ProposedValue : value[i]; + object? proposed = (null != e) ? e.ProposedValue : item; if (null == proposed) { if (column.IsValueType) @@ -690,7 +702,7 @@ namespace System.Data /// /// Sets the error description for a column specified by index. /// - public void SetColumnError(int columnIndex, string error) + public void SetColumnError(int columnIndex, string? error) { DataColumn column = _columns[columnIndex]; if (column == null) @@ -703,7 +715,7 @@ namespace System.Data /// /// Sets the error description for a column specified by name. /// - public void SetColumnError(string columnName, string error) + public void SetColumnError(string columnName, string? error) { DataColumn column = GetDataColumn(columnName); SetColumnError(column, error); @@ -712,7 +724,7 @@ namespace System.Data /// /// Sets the error description for a column specified as a . /// - public void SetColumnError(DataColumn column, string error) + public void SetColumnError(DataColumn column, string? error) { CheckColumn(column); @@ -785,23 +797,23 @@ namespace System.Data public DataColumn[] GetColumnsInError() => _error == null ? Array.Empty() : _error.GetColumnsInError(); - public DataRow[] GetChildRows(string relationName) => + public DataRow[] GetChildRows(string? relationName) => GetChildRows(_table.ChildRelations[relationName], DataRowVersion.Default); - public DataRow[] GetChildRows(string relationName, DataRowVersion version) => + public DataRow[] GetChildRows(string? relationName, DataRowVersion version) => GetChildRows(_table.ChildRelations[relationName], version); /// /// Gets the child rows of this using the /// specified . /// - public DataRow[] GetChildRows(DataRelation relation) => + public DataRow[] GetChildRows(DataRelation? relation) => GetChildRows(relation, DataRowVersion.Default); /// /// Gets the child rows of this using the specified and the specified /// - public DataRow[] GetChildRows(DataRelation relation, DataRowVersion version) + public DataRow[] GetChildRows(DataRelation? relation, DataRowVersion version) { if (relation == null) { @@ -821,7 +833,7 @@ namespace System.Data internal DataColumn GetDataColumn(string columnName) { - DataColumn column = _columns[columnName]; + DataColumn? column = _columns[columnName]; if (null != column) { return column; @@ -829,23 +841,23 @@ namespace System.Data throw ExceptionBuilder.ColumnNotInTheTable(columnName, _table.TableName); } - public DataRow GetParentRow(string relationName) => + public DataRow? GetParentRow(string? relationName) => GetParentRow(_table.ParentRelations[relationName], DataRowVersion.Default); - public DataRow GetParentRow(string relationName, DataRowVersion version) => + public DataRow? GetParentRow(string? relationName, DataRowVersion version) => GetParentRow(_table.ParentRelations[relationName], version); /// /// Gets the parent row of this using the specified . /// - public DataRow GetParentRow(DataRelation relation) => + public DataRow? GetParentRow(DataRelation? relation) => GetParentRow(relation, DataRowVersion.Default); /// /// Gets the parent row of this /// using the specified and . /// - public DataRow GetParentRow(DataRelation relation, DataRowVersion version) + public DataRow? GetParentRow(DataRelation? relation, DataRowVersion version) { if (relation == null) { @@ -867,7 +879,7 @@ namespace System.Data // a multiple nested child table's row can have only one non-null FK per row. So table has multiple // parents, but a row can have only one parent. Same nested row cannot below to 2 parent rows. - internal DataRow GetNestedParentRow(DataRowVersion version) + internal DataRow? GetNestedParentRow(DataRowVersion version) { // 1) Walk over all FKs and get the non-null. 2) Get the relation. 3) Get the parent Row. DataRelation[] nestedParentRelations = _table.NestedParentRelations; @@ -882,7 +894,7 @@ namespace System.Data CheckForLoops(rel); } - DataRow row = GetParentRow(rel, version); + DataRow? row = GetParentRow(rel, version); if (row != null) { return row; @@ -892,22 +904,22 @@ namespace System.Data } // No Nested in 1-many - public DataRow[] GetParentRows(string relationName) => + public DataRow[] GetParentRows(string? relationName) => GetParentRows(_table.ParentRelations[relationName], DataRowVersion.Default); - public DataRow[] GetParentRows(string relationName, DataRowVersion version) => + public DataRow[] GetParentRows(string? relationName, DataRowVersion version) => GetParentRows(_table.ParentRelations[relationName], version); /// /// Gets the parent rows of this using the specified . /// - public DataRow[] GetParentRows(DataRelation relation) => + public DataRow[] GetParentRows(DataRelation? relation) => GetParentRows(relation, DataRowVersion.Default); /// /// Gets the parent rows of this using the specified . /// - public DataRow[] GetParentRows(DataRelation relation, DataRowVersion version) + public DataRow[] GetParentRows(DataRelation? relation, DataRowVersion version) { if (relation == null) { @@ -1174,7 +1186,7 @@ namespace System.Data { if (!dc.ImplementsIRevertibleChangeTracking) { - object value = null; + object? value = null; if (RowState != DataRowState.Deleted) value = this[dc]; else @@ -1183,7 +1195,7 @@ namespace System.Data { if (((IChangeTracking)value).IsChanged) { - throw ExceptionBuilder.UDTImplementsIChangeTrackingButnotIRevertible(dc.DataType.AssemblyQualifiedName); + throw ExceptionBuilder.UDTImplementsIChangeTrackingButnotIRevertible(dc.DataType.AssemblyQualifiedName!); } } } @@ -1191,7 +1203,7 @@ namespace System.Data } foreach (DataColumn dc in _columns.ColumnsImplementingIChangeTracking) { - object value = null; + object? value = null; if (RowState != DataRowState.Deleted) value = this[dc]; else @@ -1252,7 +1264,7 @@ namespace System.Data this[column] = DBNull.Value; } - internal void SetNestedParentRow(DataRow parentRow, bool setNonNested) + internal void SetNestedParentRow(DataRow? parentRow, bool setNonNested) { if (parentRow == null) { @@ -1285,7 +1297,7 @@ namespace System.Data } } - public void SetParentRow(DataRow parentRow) + public void SetParentRow(DataRow? parentRow) { SetNestedParentRow(parentRow, true); } @@ -1293,7 +1305,7 @@ namespace System.Data /// /// Sets current row's parent row with specified relation. /// - public void SetParentRow(DataRow parentRow, DataRelation relation) + public void SetParentRow(DataRow? parentRow, DataRelation? relation) { if (relation == null) { @@ -1386,7 +1398,7 @@ namespace System.Data //Copy original record for the row in Unchanged, Modified, Deleted state. for (int i = 0; i < _columns.Count; i++) { - _columns[i].CopyValueIntoStore(_oldRecord, storeList[i], (BitArray)nullbitList[i], storeIndex); + _columns[i].CopyValueIntoStore(_oldRecord, storeList[i]!, (BitArray)nullbitList[i]!, storeIndex); } recordCount++; storeIndex++; @@ -1398,7 +1410,7 @@ namespace System.Data //Copy current record for the row in Added, Modified state. for (int i = 0; i < _columns.Count; i++) { - _columns[i].CopyValueIntoStore(_newRecord, storeList[i], (BitArray)nullbitList[i], storeIndex); + _columns[i].CopyValueIntoStore(_newRecord, storeList[i]!, (BitArray)nullbitList[i]!, storeIndex); } recordCount++; storeIndex++; @@ -1409,7 +1421,7 @@ namespace System.Data //Copy temp record for the row in edit mode. for (int i = 0; i < _columns.Count; i++) { - _columns[i].CopyValueIntoStore(_tempRecord, storeList[i], (BitArray)nullbitList[i], storeIndex); + _columns[i].CopyValueIntoStore(_tempRecord, storeList[i]!, (BitArray)nullbitList[i]!, storeIndex); } recordCount++; storeIndex++; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs index a1df387..9a2daa6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowCollection.cs @@ -11,11 +11,11 @@ namespace System.Data { internal DataRowTree() : base(TreeAccessMethod.INDEX_ONLY) { } - protected override int CompareNode(DataRow record1, DataRow record2) + protected override int CompareNode(DataRow? record1, DataRow? record2) { throw ExceptionBuilder.InternalRBTreeError(RBTreeError.CompareNodeInDataRowTree); } - protected override int CompareSateliteTreeNode(DataRow record1, DataRow record2) + protected override int CompareSateliteTreeNode(DataRow? record1, DataRow? record2) { throw ExceptionBuilder.InternalRBTreeError(RBTreeError.CompareSateliteTreeNodeInDataRowTree); } @@ -99,7 +99,7 @@ namespace System.Data } } - public int IndexOf(DataRow row) => (null == row) || (row.Table != _table) || ((0 == row.RBTreeNodeId) && (row.RowState == DataRowState.Detached)) ? + public int IndexOf(DataRow? row) => (null == row) || (row.Table != _table) || ((0 == row.RBTreeNodeId) && (row.RowState == DataRowState.Detached)) ? -1 : _list.IndexOf(row.RBTreeNodeId, row); @@ -114,7 +114,7 @@ namespace System.Data return row; } - public DataRow Add(params object[] values) + public DataRow Add(params object?[] values) { int record = _table.NewRecordFromArray(values); DataRow row = _table.NewRow(record); @@ -141,12 +141,12 @@ namespace System.Data /// /// Gets the row specified by the primary key value. /// - public DataRow Find(object key) => _table.FindByPrimaryKey(key); + public DataRow? Find(object? key) => _table.FindByPrimaryKey(key); /// /// Gets the row containing the specified primary key values. /// - public DataRow Find(object[] keys) => _table.FindByPrimaryKey(keys); + public DataRow? Find(object?[] keys) => _table.FindByPrimaryKey(keys); /// /// Clears the collection of all rows. @@ -157,13 +157,13 @@ namespace System.Data /// Gets a value indicating whether the primary key of any row in the /// collection contains the specified value. /// - public bool Contains(object key) => (_table.FindByPrimaryKey(key) != null); + public bool Contains(object? key) => (_table.FindByPrimaryKey(key) != null); /// /// Gets a value indicating if the with /// the specified primary key values exists. /// - public bool Contains(object[] keys) => (_table.FindByPrimaryKey(keys) != null); + public bool Contains(object?[] keys) => (_table.FindByPrimaryKey(keys) != null); public override void CopyTo(Array ar, int index) => _list.CopyTo(ar, index); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs index 46699fe..045f152 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowComparer.cs @@ -17,7 +17,7 @@ namespace System.Data /// public static DataRowComparer Default { get { return DataRowComparer.Default; } } - internal static bool AreEqual(object a, object b) + internal static bool AreEqual(object? a, object? b) { if (ReferenceEquals(a, b)) { @@ -33,7 +33,7 @@ namespace System.Data return (a.Equals(b) || (a.GetType().IsArray && CompareArray((Array)a, b as Array))); } - private static bool AreElementEqual(object a, object b) + private static bool AreElementEqual(object? a, object? b) { if (ReferenceEquals(a, b)) { @@ -49,7 +49,7 @@ namespace System.Data return a.Equals(b); } - private static bool CompareArray(Array a, Array b) + private static bool CompareArray(Array a, Array? b) { if ((null == b) || (1 != a.Rank) || @@ -74,8 +74,10 @@ namespace System.Data return CompareEquatableArray((int[])a, (int[])b); case TypeCode.Int64: return CompareEquatableArray((long[])a, (long[])b); +#nullable disable case TypeCode.String: return CompareEquatableArray((string[])a, (string[])b); +#nullable enable } } @@ -134,7 +136,7 @@ namespace System.Data /// The first input DataRow /// The second input DataRow /// True if rows are equal, false if not. - public bool Equals(TRow leftRow, TRow rightRow) + public bool Equals(TRow? leftRow, TRow? rightRow) { if (ReferenceEquals(leftRow, rightRow)) { @@ -192,7 +194,7 @@ namespace System.Data Type valueType = value.GetType(); if (valueType.IsArray) { - Array array = value as Array; + Array array = (Array)value; if (array.Rank > 1) { @@ -200,7 +202,7 @@ namespace System.Data } else if (array.Length > 0) { - hash = array.GetValue(array.GetLowerBound(0)).GetHashCode(); + hash = array.GetValue(array.GetLowerBound(0))!.GetHashCode(); } } else diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowCreatedEventHandler.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowCreatedEventHandler.cs index 4d6fb27..972da11 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowCreatedEventHandler.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowCreatedEventHandler.cs @@ -4,5 +4,5 @@ namespace System.Data { internal delegate void DataRowCreatedEventHandler(object sender, DataRow r); - internal delegate void DataSetClearEventhandler(object sender, DataTable table); + internal delegate void DataSetClearEventhandler(object sender, DataTable? table); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowExtensions.cs index 5629487..afa65a3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowExtensions.cs @@ -1,16 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; namespace System.Data { - /// /// This static class defines the DataRow extension methods. /// public static class DataRowExtensions { - /// /// This method provides access to the values in each of the columns in a given row. /// This method makes casts unnecessary when accessing columns. @@ -20,6 +19,7 @@ namespace System.Data /// The input DataRow /// The input column name specifying which row value to retrieve. /// The DataRow value for the column specified. + [return: MaybeNull] public static T Field(this DataRow row, string columnName) { DataSetUtil.CheckArgumentNull(row, nameof(row)); @@ -35,6 +35,7 @@ namespace System.Data /// The input DataRow /// The input DataColumn specifying which row value to retrieve. /// The DataRow value for the column specified. + [return: MaybeNull] public static T Field(this DataRow row, DataColumn column) { DataSetUtil.CheckArgumentNull(row, nameof(row)); @@ -50,6 +51,7 @@ namespace System.Data /// The input DataRow /// The input ordinal specifying which row value to retrieve. /// The DataRow value for the column specified. + [return: MaybeNull] public static T Field(this DataRow row, int columnIndex) { DataSetUtil.CheckArgumentNull(row, nameof(row)); @@ -66,6 +68,7 @@ namespace System.Data /// The input ordinal specifying which row value to retrieve. /// The DataRow version for which row value to retrieve. /// The DataRow value for the column specified. + [return: MaybeNull] public static T Field(this DataRow row, int columnIndex, DataRowVersion version) { DataSetUtil.CheckArgumentNull(row, nameof(row)); @@ -82,6 +85,7 @@ namespace System.Data /// The input column name specifying which row value to retrieve. /// The DataRow version for which row value to retrieve. /// The DataRow value for the column specified. + [return: MaybeNull] public static T Field(this DataRow row, string columnName, DataRowVersion version) { DataSetUtil.CheckArgumentNull(row, nameof(row)); @@ -98,6 +102,7 @@ namespace System.Data /// The input DataColumn specifying which row value to retrieve. /// The DataRow version for which row value to retrieve. /// The DataRow value for the column specified. + [return: MaybeNull] public static T Field(this DataRow row, DataColumn column, DataRowVersion version) { DataSetUtil.CheckArgumentNull(row, nameof(row)); @@ -110,10 +115,10 @@ namespace System.Data /// The input DataRow. /// The input ordinal specifying which row value to set. /// The new row value for the specified column. - public static void SetField(this DataRow row, int columnIndex, T value) + public static void SetField(this DataRow row, int columnIndex, [AllowNull] T value) { DataSetUtil.CheckArgumentNull(row, nameof(row)); - row[columnIndex] = (object)value ?? DBNull.Value; + row[columnIndex] = (object?)value ?? DBNull.Value; } /// @@ -122,10 +127,10 @@ namespace System.Data /// The input DataRow. /// The input column name specifying which row value to retrieve. /// The new row value for the specified column. - public static void SetField(this DataRow row, string columnName, T value) + public static void SetField(this DataRow row, string columnName, [AllowNull] T value) { DataSetUtil.CheckArgumentNull(row, nameof(row)); - row[columnName] = (object)value ?? DBNull.Value; + row[columnName] = (object?)value ?? DBNull.Value; } /// @@ -134,10 +139,10 @@ namespace System.Data /// The input DataRow. /// The input DataColumn specifying which row value to retrieve. /// The new row value for the specified column. - public static void SetField(this DataRow row, DataColumn column, T value) + public static void SetField(this DataRow row, DataColumn column, [AllowNull] T value) { DataSetUtil.CheckArgumentNull(row, nameof(row)); - row[column] = (object)value ?? DBNull.Value; + row[column] = (object?)value ?? DBNull.Value; } private static class UnboxT @@ -152,7 +157,7 @@ namespace System.Data ? (Converter)Delegate.CreateDelegate( typeof(Converter), typeof(UnboxT) - .GetMethod("NullableField", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic) + .GetMethod("NullableField", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)! .MakeGenericMethod(typeof(T).GetGenericArguments()[0])) : ValueField; } @@ -160,6 +165,7 @@ namespace System.Data return ReferenceField; } + [return: MaybeNull] private static T ReferenceField(object value) => value == DBNull.Value ? default : (T)value; @@ -168,6 +174,7 @@ namespace System.Data ? throw DataSetUtil.InvalidCast(SR.Format(SR.DataSetLinq_NonNullableCast, typeof(T))) : (T)value; + [return: MaybeNull] private static Nullable NullableField(object value) where TElem : struct => value == DBNull.Value ? default : new Nullable((TElem)value); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs index 5debc95..8f0813b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -27,7 +28,7 @@ namespace System.Data /// to understand if they need to add a event handler. /// /// - public override bool Equals(object other) => ReferenceEquals(this, other); + public override bool Equals(object? other) => ReferenceEquals(this, other); /// Hashcode of public override int GetHashCode() @@ -48,6 +49,7 @@ namespace System.Data /// Uses either or to access /// when setting a value. /// + [AllowNull] public object this[int ndx] { get { return Row[ndx, RowVersionDefault]; } @@ -57,7 +59,7 @@ namespace System.Data { throw ExceptionBuilder.CanNotEdit(); } - SetColumnValue(_dataView.Table.Columns[ndx], value); + SetColumnValue(_dataView.Table!.Columns[ndx], value); } } @@ -67,11 +69,12 @@ namespace System.Data /// Unmatched when getting a value. /// Unmatched when setting a value. /// when setting a value. + [AllowNull] public object this[string property] { get { - DataColumn column = _dataView.Table.Columns[property]; + DataColumn? column = _dataView.Table!.Columns[property]; if (null != column) { return Row[column, RowVersionDefault]; @@ -84,7 +87,7 @@ namespace System.Data } set { - DataColumn column = _dataView.Table.Columns[property]; + DataColumn? column = _dataView.Table!.Columns[property]; if (null == column) { throw ExceptionBuilder.SetFailed(property); @@ -97,10 +100,13 @@ namespace System.Data } } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable // IDataErrorInfo stuff string IDataErrorInfo.this[string colName] => Row.GetColumnError(colName); string IDataErrorInfo.Error => Row.RowError; +#nullable enable /// /// Gets the current version description of the @@ -118,7 +124,7 @@ namespace System.Data internal object GetColumnValue(DataColumn column) => Row[column, RowVersionDefault]; - internal void SetColumnValue(DataColumn column, object value) + internal void SetColumnValue(DataColumn column, object? value) { if (_delayBeginEdit) { @@ -172,7 +178,7 @@ namespace System.Data /// The parent object. /// Unmatched . public DataView CreateChildView(string relationName, bool followParent) => - CreateChildView(DataView.Table.ChildRelations[relationName], followParent); + CreateChildView(DataView.Table!.ChildRelations[relationName]!, followParent); public DataView CreateChildView(string relationName) => CreateChildView(relationName, followParent: false); @@ -220,12 +226,13 @@ namespace System.Data // This is so a generic event handler like Windows Presentation Foundation can redirect as appropriate. // Having DataView.Equals is not sufficient for WPF, because two different instances may be equal but not equivalent. // For DataRowView, if two instances are equal then they are equivalent. - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; // Do not try catch, we would mask users bugs. if they throw we would catch internal void RaisePropertyChangedEvent(string propName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName)); #region ICustomTypeDescriptor +#nullable disable AttributeCollection ICustomTypeDescriptor.GetAttributes() => new AttributeCollection(null); string ICustomTypeDescriptor.GetClassName() => null; string ICustomTypeDescriptor.GetComponentName() => null; @@ -239,6 +246,7 @@ namespace System.Data PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) => (_dataView.Table != null ? _dataView.Table.GetPropertyDescriptorCollection(attributes) : s_zeroPropertyDescriptorCollection); object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) => this; +#nullable enable #endregion } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index a5daf7d..2c96c7a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; @@ -32,12 +33,12 @@ namespace System.Data private const string KEY_XMLSCHEMA = "XmlSchema"; private const string KEY_XMLDIFFGRAM = "XmlDiffGram"; - private DataViewManager _defaultViewManager; + private DataViewManager? _defaultViewManager; // Public Collections private readonly DataTableCollection _tableCollection; private readonly DataRelationCollection _relationCollection; - internal PropertyCollection _extendedProperties; + internal PropertyCollection? _extendedProperties; private string _dataSetName = "NewDataSet"; private string _datasetPrefix = string.Empty; internal string _namespaceURI = string.Empty; @@ -66,7 +67,7 @@ namespace System.Data private static int s_objectTypeCount; // Bid counter private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount); - private static XmlSchemaComplexType s_schemaTypeForWSDL; + private static XmlSchemaComplexType? s_schemaTypeForWSDL; internal bool _useDataSetSchemaOnly; // UseDataSetSchemaOnly , for YUKON internal bool _udtIsWrapped; // if UDT is wrapped , for YUKON @@ -142,7 +143,7 @@ namespace System.Data if (e.Name == "DataSet.RemotingFormat") { //DataSet.RemotingFormat does not exist in V1/V1.1 versions - remotingFormat = (SerializationFormat)e.Value; + remotingFormat = (SerializationFormat)e.Value!; break; } } @@ -162,7 +163,7 @@ namespace System.Data { if (e.Name == "SchemaSerializationMode.DataSet") { //SchemaSerializationMode.DataSet does not exist in V1/V1.1 versions - schemaSerializationMode = (SchemaSerializationMode)e.Value; + schemaSerializationMode = (SchemaSerializationMode)e.Value!; break; } } @@ -210,7 +211,7 @@ namespace System.Data { if (e.Name == "DataSet.RemotingFormat") { //DataSet.RemotingFormat does not exist in V1/V1.1 versions - remotingFormat = (SerializationFormat)e.Value; + remotingFormat = (SerializationFormat)e.Value!; break; } } @@ -235,10 +236,10 @@ namespace System.Data switch (e.Name) { case "DataSet.RemotingFormat": //DataSet.RemotingFormat does not exist in V1/V1.1 versions - remotingFormat = (SerializationFormat)e.Value; + remotingFormat = (SerializationFormat)e.Value!; break; case "SchemaSerializationMode.DataSet": //SchemaSerializationMode.DataSet does not exist in V1/V1.1 versions - schemaSerializationMode = (SchemaSerializationMode)e.Value; + schemaSerializationMode = (SchemaSerializationMode)e.Value!; break; } } @@ -340,7 +341,7 @@ namespace System.Data // old behaviour string strSchema = GetXmlSchemaForRemoting(null); - string strData = null; + string? strData = null; info.AddValue(KEY_XMLSCHEMA, strSchema); StringBuilder strBuilder = new StringBuilder(EstimatedXmlStringSize() * 2); @@ -377,7 +378,7 @@ namespace System.Data //Tables, Columns, Rows for (int i = 0; i < tableCount; i++) { - byte[] buffer = (byte[])info.GetValue(string.Format(CultureInfo.InvariantCulture, "DataSet.Tables_{0}", i), typeof(byte[])); + byte[] buffer = (byte[])info.GetValue(string.Format(CultureInfo.InvariantCulture, "DataSet.Tables_{0}", i), typeof(byte[]))!; MemoryStream memStream = new MemoryStream(buffer); memStream.Position = 0; BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(context.State, false)); @@ -408,7 +409,7 @@ namespace System.Data } else { - string strSchema = (string)info.GetValue(KEY_XMLSCHEMA, typeof(string)); + string? strSchema = (string?)info.GetValue(KEY_XMLSCHEMA, typeof(string)); if (strSchema != null) { @@ -429,7 +430,7 @@ namespace System.Data } else { - string strData = (string)info.GetValue(KEY_XMLDIFFGRAM, typeof(string)); + string? strData = (string?)info.GetValue(KEY_XMLDIFFGRAM, typeof(string)); if (strData != null) { @@ -459,19 +460,19 @@ namespace System.Data private void DeserializeDataSetProperties(SerializationInfo info, StreamingContext context) { //DataSet basic properties - _dataSetName = info.GetString("DataSet.DataSetName"); - _namespaceURI = info.GetString("DataSet.Namespace"); - _datasetPrefix = info.GetString("DataSet.Prefix"); + _dataSetName = info.GetString("DataSet.DataSetName")!; + _namespaceURI = info.GetString("DataSet.Namespace")!; + _datasetPrefix = info.GetString("DataSet.Prefix")!; //DataSet runtime properties _caseSensitive = info.GetBoolean("DataSet.CaseSensitive"); - int lcid = (int)info.GetValue("DataSet.LocaleLCID", typeof(int)); + int lcid = (int)info.GetValue("DataSet.LocaleLCID", typeof(int))!; _culture = new CultureInfo(lcid); _cultureUserSet = true; _enforceConstraints = info.GetBoolean("DataSet.EnforceConstraints"); //ExtendedProperties - _extendedProperties = (PropertyCollection)info.GetValue("DataSet.ExtendedProperties", typeof(PropertyCollection)); + _extendedProperties = (PropertyCollection?)info.GetValue("DataSet.ExtendedProperties", typeof(PropertyCollection)); } // Gets relation info from the dataset. @@ -515,15 +516,15 @@ namespace System.Data // Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties] private void DeserializeRelations(SerializationInfo info, StreamingContext context) { - ArrayList relationList = (ArrayList)info.GetValue("DataSet.Relations", typeof(ArrayList)); + ArrayList relationList = (ArrayList)info.GetValue("DataSet.Relations", typeof(ArrayList))!; foreach (ArrayList list in relationList) { - string relationName = (string)list[0]; - int[] parentInfo = (int[])list[1]; - int[] childInfo = (int[])list[2]; - bool isNested = (bool)list[3]; - PropertyCollection extendedProperties = (PropertyCollection)list[4]; + string relationName = (string)list[0]!; + int[] parentInfo = (int[])list[1]!; + int[] childInfo = (int[])list[2]!; + bool isNested = (bool)list[3]!; + PropertyCollection? extendedProperties = (PropertyCollection?)list[4]!; //ParentKey Columns. DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1]; @@ -586,7 +587,10 @@ namespace System.Data } } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable bool IListSource.ContainsListCollection => true; +#nullable enable /// /// Gets a custom view of the data contained by the , one @@ -700,7 +704,7 @@ namespace System.Data throw ExceptionBuilder.SetDataSetNameToEmpty(); } - DataTable conflicting = Tables[value, Namespace]; + DataTable? conflicting = Tables[value, Namespace]; if ((conflicting != null) && (!conflicting._fNestedInDataset)) { throw ExceptionBuilder.SetDataSetNameConflicting(value); @@ -713,6 +717,7 @@ namespace System.Data } [DefaultValue("")] + [AllowNull] public string Namespace { get { return _namespaceURI; } @@ -756,6 +761,7 @@ namespace System.Data } [DefaultValue("")] + [AllowNull] public string Prefix { get { return _datasetPrefix; } @@ -928,6 +934,8 @@ namespace System.Data return _cultureUserSet; } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override ISite Site @@ -954,6 +962,7 @@ namespace System.Data base.Site = value; } } +#nullable enable /// /// Get the collection of relations that link tables and @@ -1014,17 +1023,17 @@ namespace System.Data } } - internal event PropertyChangedEventHandler PropertyChanging; + internal event PropertyChangedEventHandler? PropertyChanging; /// /// Occurs when attempting to merge schemas for two tables with the same name. /// - public event MergeFailedEventHandler MergeFailed; + public event MergeFailedEventHandler? MergeFailed; - internal event DataRowCreatedEventHandler DataRowCreated; // Internal for XmlDataDocument only - internal event DataSetClearEventhandler ClearFunctionCalled; // Internal for XmlDataDocument only + internal event DataRowCreatedEventHandler? DataRowCreated; // Internal for XmlDataDocument only + internal event DataSetClearEventhandler? ClearFunctionCalled; // Internal for XmlDataDocument only - public event EventHandler Initialized; + public event EventHandler? Initialized; public void BeginInit() { @@ -1084,7 +1093,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { - DataSet ds = (DataSet)Activator.CreateInstance(GetType(), true); + DataSet ds = (DataSet)Activator.CreateInstance(GetType(), true)!; if (ds.Tables.Count > 0) // To clean up all the schema in strong typed dataset. { @@ -1123,13 +1132,13 @@ namespace System.Data continue; } - ForeignKeyConstraint foreign = constraints[j] as ForeignKeyConstraint; + ForeignKeyConstraint foreign = (ForeignKeyConstraint)constraints[j]; if (foreign.Table == foreign.RelatedTable) { continue; // we have already added this foreign key in while cloning the datatable } - ds.Tables[i].Constraints.Add(constraints[j].Clone(ds)); + ds.Tables[i].Constraints.Add(constraints[j].Clone(ds)!); } } @@ -1158,7 +1167,7 @@ namespace System.Data { if (col.Expression.Length != 0) { - ds.Tables[table.TableName, table.Namespace].Columns[col.ColumnName].Expression = col.Expression; + ds.Tables[table.TableName, table.Namespace]!.Columns[col.ColumnName]!.Expression = col.Expression; } } } @@ -1191,7 +1200,7 @@ namespace System.Data dsNew.EnforceConstraints = false; foreach (DataTable table in Tables) { - DataTable destTable = dsNew.Tables[table.TableName, table.Namespace]; + DataTable destTable = dsNew.Tables[table.TableName, table.Namespace]!; foreach (DataRow row in table.Rows) { @@ -1231,7 +1240,7 @@ namespace System.Data /// Returns a copy of the that contains all changes made to /// it since it was loaded or was last called. /// - public DataSet GetChanges() => + public DataSet? GetChanges() => GetChanges(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified); private struct TableChanges @@ -1258,12 +1267,12 @@ namespace System.Data } } - public DataSet GetChanges(DataRowState rowStates) + public DataSet? GetChanges(DataRowState rowStates) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, rowStates={1}", ObjectID, rowStates); try { - DataSet dsNew = null; + DataSet? dsNew = null; bool fEnforceConstraints = false; if (0 != (rowStates & ~(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified | DataRowState.Unchanged))) { @@ -1294,7 +1303,7 @@ namespace System.Data } DataTable table = Tables[i]; - DataTable destTable = dsNew.Tables[table.TableName, table.Namespace]; + DataTable destTable = dsNew.Tables[table.TableName, table.Namespace]!; Debug.Assert(bitMatrix[i].HasChanges <= table.Rows.Count, "to many changes"); for (int j = 0; 0 < bitMatrix[i].HasChanges; ++j) @@ -1380,18 +1389,18 @@ namespace System.Data } } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable IList IListSource.GetList() => DefaultViewManager; +#nullable enable internal string GetRemotingDiffGram(DataTable table) { StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter); writer.Formatting = Formatting.Indented; - if (strWriter != null) - { - // Create and save the updates - new NewDiffgramGen(table, false).Save(writer, table); - } + // Create and save the updates + new NewDiffgramGen(table, false).Save(writer, table); return strWriter.ToString(); } @@ -1404,12 +1413,9 @@ namespace System.Data // StringBuilder strBuilder = new StringBuilder(EstimatedXmlStringSize()); // StringWriter strWriter = new StringWriter(strBuilder); StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); - if (strWriter != null) - { - XmlTextWriter w = new XmlTextWriter(strWriter); - w.Formatting = Formatting.Indented; - new XmlDataTreeWriter(this).Save(w, false); - } + XmlTextWriter w = new XmlTextWriter(strWriter); + w.Formatting = Formatting.Indented; + new XmlDataTreeWriter(this).Save(w, false); return strWriter.ToString(); } finally @@ -1426,10 +1432,7 @@ namespace System.Data StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter); writer.Formatting = Formatting.Indented; - if (strWriter != null) - { - (new XmlTreeGen(SchemaFormat.Public)).Save(this, writer); - } + (new XmlTreeGen(SchemaFormat.Public)).Save(this, writer); return strWriter.ToString(); } @@ -1439,30 +1442,27 @@ namespace System.Data } } - internal string GetXmlSchemaForRemoting(DataTable table) + internal string GetXmlSchemaForRemoting(DataTable? table) { StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter); writer.Formatting = Formatting.Indented; - if (strWriter != null) + if (table == null) { - if (table == null) + if (SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema) { - if (SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema) - { - (new XmlTreeGen(SchemaFormat.RemotingSkipSchema)).Save(this, writer); - } - else - { - (new XmlTreeGen(SchemaFormat.Remoting)).Save(this, writer); - } + (new XmlTreeGen(SchemaFormat.RemotingSkipSchema)).Save(this, writer); } else { - // no skip schema support for typed datatable - (new XmlTreeGen(SchemaFormat.Remoting)).Save(table, writer); + (new XmlTreeGen(SchemaFormat.Remoting)).Save(this, writer); } } + else + { + // no skip schema support for typed datatable + (new XmlTreeGen(SchemaFormat.Remoting)).Save(table, writer); + } return strWriter.ToString(); } @@ -1514,7 +1514,7 @@ namespace System.Data /// /// Infer the XML schema from the specified into the . /// - public void InferXmlSchema(XmlReader reader, string[] nsArray) + public void InferXmlSchema(XmlReader? reader, string[]? nsArray) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try @@ -1551,7 +1551,7 @@ namespace System.Data /// /// Infer the XML schema from the specified into the . /// - public void InferXmlSchema(Stream stream, string[] nsArray) + public void InferXmlSchema(Stream? stream, string[]? nsArray) { if (stream == null) { @@ -1564,7 +1564,7 @@ namespace System.Data /// /// Infer the XML schema from the specified into the . /// - public void InferXmlSchema(TextReader reader, string[] nsArray) + public void InferXmlSchema(TextReader? reader, string[]? nsArray) { if (reader == null) { @@ -1577,7 +1577,7 @@ namespace System.Data /// /// Infer the XML schema from the specified file into the . /// - public void InferXmlSchema(string fileName, string[] nsArray) + public void InferXmlSchema(string fileName, string[]? nsArray) { XmlTextReader xr = new XmlTextReader(fileName); try @@ -1593,9 +1593,9 @@ namespace System.Data /// /// Reads the XML schema from the specified into the /// - public void ReadXmlSchema(XmlReader reader) => ReadXmlSchema(reader, false); + public void ReadXmlSchema(XmlReader? reader) => ReadXmlSchema(reader, false); - internal void ReadXmlSchema(XmlReader reader, bool denyResolving) + internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, reader, denyResolving={1}", ObjectID, denyResolving); try @@ -1792,7 +1792,7 @@ namespace System.Data /// Reads the XML schema from the specified into the /// . /// - public void ReadXmlSchema(Stream stream) + public void ReadXmlSchema(Stream? stream) { if (stream == null) { @@ -1805,7 +1805,7 @@ namespace System.Data /// /// Reads the XML schema from the specified into the . /// - public void ReadXmlSchema(TextReader reader) + public void ReadXmlSchema(TextReader? reader) { if (reader == null) { @@ -1834,12 +1834,12 @@ namespace System.Data #region WriteXmlSchema /// Writes the structure as an XML schema to using the specified object. /// A object used to write to a file. - public void WriteXmlSchema(Stream stream) => WriteXmlSchema(stream, SchemaFormat.Public, null); + public void WriteXmlSchema(Stream? stream) => WriteXmlSchema(stream, SchemaFormat.Public, null); /// Writes the structure as an XML schema to using the specified object. /// A object used to write to a file. /// A delegate used to convert into string. - public void WriteXmlSchema(Stream stream, Converter multipleTargetConverter) + public void WriteXmlSchema(Stream? stream, Converter multipleTargetConverter) { ADP.CheckArgumentNull(multipleTargetConverter, nameof(multipleTargetConverter)); WriteXmlSchema(stream, SchemaFormat.Public, multipleTargetConverter); @@ -1860,12 +1860,12 @@ namespace System.Data /// Writes the structure as an XML schema to a object. /// The object with which to write. - public void WriteXmlSchema(TextWriter writer) => WriteXmlSchema(writer, SchemaFormat.Public, null); + public void WriteXmlSchema(TextWriter? writer) => WriteXmlSchema(writer, SchemaFormat.Public, null); /// Writes the structure as an XML schema to a object. /// The object with which to write. /// A delegate used to convert into string. - public void WriteXmlSchema(TextWriter writer, Converter multipleTargetConverter) + public void WriteXmlSchema(TextWriter? writer, Converter multipleTargetConverter) { ADP.CheckArgumentNull(multipleTargetConverter, nameof(multipleTargetConverter)); WriteXmlSchema(writer, SchemaFormat.Public, multipleTargetConverter); @@ -1873,18 +1873,18 @@ namespace System.Data /// Writes the structure as an XML schema to an object. /// The object with which to write. - public void WriteXmlSchema(XmlWriter writer) => WriteXmlSchema(writer, SchemaFormat.Public, null); + public void WriteXmlSchema(XmlWriter? writer) => WriteXmlSchema(writer, SchemaFormat.Public, null); /// Writes the structure as an XML schema to an object. /// The object with which to write. /// A delegate used to convert into string. - public void WriteXmlSchema(XmlWriter writer, Converter multipleTargetConverter) + public void WriteXmlSchema(XmlWriter? writer, Converter multipleTargetConverter) { ADP.CheckArgumentNull(multipleTargetConverter, nameof(multipleTargetConverter)); WriteXmlSchema(writer, SchemaFormat.Public, multipleTargetConverter); } - private void WriteXmlSchema(string fileName, SchemaFormat schemaFormat, Converter multipleTargetConverter) + private void WriteXmlSchema(string fileName, SchemaFormat schemaFormat, Converter? multipleTargetConverter) { XmlTextWriter xw = new XmlTextWriter(fileName, null); try @@ -1900,7 +1900,7 @@ namespace System.Data } } - private void WriteXmlSchema(Stream stream, SchemaFormat schemaFormat, Converter multipleTargetConverter) + private void WriteXmlSchema(Stream? stream, SchemaFormat schemaFormat, Converter? multipleTargetConverter) { if (stream == null) { @@ -1913,7 +1913,7 @@ namespace System.Data WriteXmlSchema(w, schemaFormat, multipleTargetConverter); } - private void WriteXmlSchema(TextWriter writer, SchemaFormat schemaFormat, Converter multipleTargetConverter) + private void WriteXmlSchema(TextWriter? writer, SchemaFormat schemaFormat, Converter? multipleTargetConverter) { if (writer == null) { @@ -1926,7 +1926,7 @@ namespace System.Data WriteXmlSchema(w, schemaFormat, multipleTargetConverter); } - private void WriteXmlSchema(XmlWriter writer, SchemaFormat schemaFormat, Converter multipleTargetConverter) + private void WriteXmlSchema(XmlWriter? writer, SchemaFormat schemaFormat, Converter? multipleTargetConverter) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, schemaFormat={1}", ObjectID, schemaFormat); try @@ -1934,7 +1934,7 @@ namespace System.Data // Generate SchemaTree and write it out if (writer != null) { - XmlTreeGen treeGen = null; + XmlTreeGen? treeGen = null; if (schemaFormat == SchemaFormat.WebService && SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema && writer.WriteState == WriteState.Element) @@ -1995,7 +1995,7 @@ namespace System.Data } XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema - XmlDataLoader xmlload = null; + XmlDataLoader? xmlload = null; reader.MoveToContent(); @@ -2281,7 +2281,7 @@ namespace System.Data } } - internal void InferSchema(XmlDocument xdoc, string[] excludedNamespaces, XmlReadMode mode) + internal void InferSchema(XmlDocument xdoc, string[]? excludedNamespaces, XmlReadMode mode) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, mode={1}", ObjectID, mode); try @@ -2462,9 +2462,9 @@ namespace System.Data /// /// - public XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode) => ReadXml(reader, mode, false); + public XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode) => ReadXml(reader, mode, false); - internal XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode, bool denyResolving) + internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResolving) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, mode={1}, denyResolving={2}", ObjectID, mode, denyResolving); try @@ -2506,11 +2506,11 @@ namespace System.Data } reader.MoveToContent(); - XmlDataLoader xmlload = null; + XmlDataLoader? xmlload = null; if (reader.NodeType == XmlNodeType.Element) { - XmlElement topNode = null; + XmlElement? topNode = null; if (mode == XmlReadMode.Fragment) { xdoc.AppendChild(xdoc.CreateElement("ds_sqlXmlWraPPeR")); @@ -2714,7 +2714,7 @@ namespace System.Data } } - public XmlReadMode ReadXml(Stream stream, XmlReadMode mode) + public XmlReadMode ReadXml(Stream? stream, XmlReadMode mode) { if (stream == null) { @@ -2727,7 +2727,7 @@ namespace System.Data return ReadXml(reader, mode, false); } - public XmlReadMode ReadXml(TextReader reader, XmlReadMode mode) + public XmlReadMode ReadXml(TextReader? reader, XmlReadMode mode) { if (reader == null) { @@ -2742,7 +2742,7 @@ namespace System.Data public XmlReadMode ReadXml(string fileName, XmlReadMode mode) { - XmlTextReader xr = null; + XmlTextReader? xr = null; if (mode == XmlReadMode.Fragment) { FileStream stream = new FileStream(fileName, FileMode.Open); @@ -2766,18 +2766,18 @@ namespace System.Data } } - public void WriteXml(Stream stream) => WriteXml(stream, XmlWriteMode.IgnoreSchema); + public void WriteXml(Stream? stream) => WriteXml(stream, XmlWriteMode.IgnoreSchema); - public void WriteXml(TextWriter writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema); + public void WriteXml(TextWriter? writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema); - public void WriteXml(XmlWriter writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema); + public void WriteXml(XmlWriter? writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema); public void WriteXml(string fileName) => WriteXml(fileName, XmlWriteMode.IgnoreSchema); /// /// Writes schema and data for the DataSet. /// - public void WriteXml(Stream stream, XmlWriteMode mode) + public void WriteXml(Stream? stream, XmlWriteMode mode) { if (stream != null) { @@ -2788,7 +2788,7 @@ namespace System.Data } } - public void WriteXml(TextWriter writer, XmlWriteMode mode) + public void WriteXml(TextWriter? writer, XmlWriteMode mode) { if (writer != null) { @@ -2799,7 +2799,7 @@ namespace System.Data } } - public void WriteXml(XmlWriter writer, XmlWriteMode mode) + public void WriteXml(XmlWriter? writer, XmlWriteMode mode) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, mode={1}", ObjectID, mode); try @@ -2833,18 +2833,15 @@ namespace System.Data { xw.Formatting = Formatting.Indented; xw.WriteStartDocument(true); - if (xw != null) + // Create and save the updates + if (mode == XmlWriteMode.DiffGram) { - // Create and save the updates - if (mode == XmlWriteMode.DiffGram) - { - new NewDiffgramGen(this).Save(xw); - } - else - { - // Create and save xml data - new XmlDataTreeWriter(this).Save(xw, mode == XmlWriteMode.WriteSchema); - } + new NewDiffgramGen(this).Save(xw); + } + else + { + // Create and save xml data + new XmlDataTreeWriter(this).Save(xw, mode == XmlWriteMode.WriteSchema); } xw.WriteEndDocument(); } @@ -2867,6 +2864,7 @@ namespace System.Data public void Merge(DataSet dataSet) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0); + Debug.Assert(dataSet != null); try { Merge(dataSet, false, MissingSchemaAction.Add); @@ -2884,6 +2882,7 @@ namespace System.Data public void Merge(DataSet dataSet, bool preserveChanges) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, dataSet={1}, preserveChanges={2}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0, preserveChanges); + Debug.Assert(dataSet != null); try { Merge(dataSet, preserveChanges, MissingSchemaAction.Add); @@ -2935,6 +2934,7 @@ namespace System.Data public void Merge(DataTable table) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}", ObjectID, (table != null) ? table.ObjectID : 0); + Debug.Assert(table != null); try { Merge(table, false, MissingSchemaAction.Add); @@ -3044,7 +3044,7 @@ namespace System.Data } } - internal void RaiseMergeFailed(DataTable table, string conflict, MissingSchemaAction missingSchemaAction) + internal void RaiseMergeFailed(DataTable? table, string conflict, MissingSchemaAction missingSchemaAction) { if (MissingSchemaAction.Error == missingSchemaAction) { @@ -3056,7 +3056,7 @@ namespace System.Data internal void OnDataRowCreated(DataRow row) => DataRowCreated?.Invoke(this, row); - internal void OnClearFunctionCalled(DataTable table) => ClearFunctionCalled?.Invoke(this, table); + internal void OnClearFunctionCalled(DataTable? table) => ClearFunctionCalled?.Invoke(this, table); private void OnInitialized() => Initialized?.Invoke(this, EventArgs.Empty); @@ -3067,7 +3067,7 @@ namespace System.Data internal void OnRemovedTable(DataTable table) { - DataViewManager viewManager = _defaultViewManager; + DataViewManager? viewManager = _defaultViewManager; if (null != viewManager) { viewManager.DataViewSettings.Remove(table); @@ -3182,7 +3182,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { - DataRelation relation = null; + DataRelation? relation = null; for (int i = 0; i < Relations.Count; i++) { relation = Relations[i]; @@ -3192,8 +3192,8 @@ namespace System.Data } } - ForeignKeyConstraint constraint = null; - ConstraintCollection constraints = null; + ForeignKeyConstraint? constraint = null; + ConstraintCollection? constraints = null; for (int i = 0; i < Tables.Count; i++) { constraints = Tables[i].Constraints; @@ -3202,7 +3202,7 @@ namespace System.Data if (constraints[j] is ForeignKeyConstraint) { constraint = (ForeignKeyConstraint)constraints[j]; - if (constraint.Table.CaseSensitive != constraint.RelatedTable.CaseSensitive) + if (constraint.Table!.CaseSensitive != constraint.RelatedTable.CaseSensitive) { return false; } @@ -3222,7 +3222,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { - DataRelation relation = null; + DataRelation? relation = null; for (int i = 0; i < Relations.Count; i++) { relation = Relations[i]; @@ -3232,8 +3232,8 @@ namespace System.Data } } - ForeignKeyConstraint constraint = null; - ConstraintCollection constraints = null; + ForeignKeyConstraint? constraint = null; + ConstraintCollection? constraints = null; for (int i = 0; i < Tables.Count; i++) { constraints = Tables[i].Constraints; @@ -3242,7 +3242,7 @@ namespace System.Data if (constraints[j] is ForeignKeyConstraint) { constraint = (ForeignKeyConstraint)constraints[j]; - if (constraint.Table.Locale.LCID != constraint.RelatedTable.Locale.LCID) + if (constraint.Table!.Locale.LCID != constraint.RelatedTable.Locale.LCID) { return false; } @@ -3258,7 +3258,7 @@ namespace System.Data } // SDUB: may be better to rewrite this as nonrecursive? - internal DataTable FindTable(DataTable baseTable, PropertyDescriptor[] props, int propStart) + internal DataTable? FindTable(DataTable? baseTable, PropertyDescriptor[] props, int propStart) { if (props.Length < propStart + 1) { @@ -3341,11 +3341,11 @@ namespace System.Data ReadXml(reader, XmlReadMode.DiffGram, true); } - protected virtual System.Xml.Schema.XmlSchema GetSchemaSerializable() => null; + protected virtual System.Xml.Schema.XmlSchema? GetSchemaSerializable() => null; public static XmlSchemaComplexType GetDataSetSchema(XmlSchemaSet schemaSet) { - // For performance resons we are exploiting the fact that config files content is constant + // For performance reasons we are exploiting the fact that config files content is constant // for a given appdomain so we can safely cache the prepared schema complex type and reuse it if (s_schemaTypeForWSDL == null) { @@ -3375,7 +3375,10 @@ namespace System.Data private static bool PublishLegacyWSDL() => false; - XmlSchema IXmlSerializable.GetSchema() +// TODO: Enable after System.Private.Xml is annotated +#nullable disable +#pragma warning disable 8632 + XmlSchema? IXmlSerializable.GetSchema() { if (GetType() == typeof(DataSet)) { @@ -3396,8 +3399,8 @@ namespace System.Data void IXmlSerializable.ReadXml(XmlReader reader) { bool fNormalization = true; - XmlTextReader xmlTextReader = null; - IXmlTextParser xmlTextParser = reader as IXmlTextParser; + XmlTextReader? xmlTextReader = null; + IXmlTextParser? xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) { fNormalization = xmlTextParser.Normalized; @@ -3430,8 +3433,10 @@ namespace System.Data WriteXmlSchema(writer, SchemaFormat.WebService, null); WriteXml(writer, XmlWriteMode.DiffGram); } +#pragma warning restore 8632 +#nullable enable - public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler, params DataTable[] tables) + public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler? errorHandler, params DataTable[] tables) { long logScopeId = DataCommonEventSource.Log.EnterScope(" reader, loadOption={0}", loadOption); try @@ -3474,7 +3479,7 @@ namespace System.Data var dataTables = new DataTable[tables.Length]; for (int i = 0; i < tables.Length; i++) { - DataTable tempDT = Tables[tables[i]]; + DataTable? tempDT = Tables[tables[i]]; if (null == tempDT) { tempDT = new DataTable(tables[i]); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 0d12ec6..e877183 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -14,6 +14,7 @@ using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Data.Common; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Data @@ -30,8 +31,8 @@ namespace System.Data [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DataTable : MarshalByValueComponent, IListSource, ISupportInitializeNotification, ISerializable, IXmlSerializable { - private DataSet _dataSet; - private DataView _defaultView; + private DataSet? _dataSet; + private DataView? _defaultView; /// /// Monotonically increasing number representing the order have been added to . @@ -50,8 +51,8 @@ namespace System.Data private int _elementColumnCount; // relations - internal DataRelationCollection _parentRelationsCollection; - internal DataRelationCollection _childRelationsCollection; + internal DataRelationCollection? _parentRelationsCollection; + internal DataRelationCollection? _childRelationsCollection; // RecordManager internal readonly RecordManager _recordManager; @@ -59,45 +60,45 @@ namespace System.Data // index mgmt internal readonly List _indexes; - private List _shadowIndexes; + private List? _shadowIndexes; private int _shadowCount; // props - internal PropertyCollection _extendedProperties; + internal PropertyCollection? _extendedProperties; private string _tableName = string.Empty; - internal string _tableNamespace; + internal string? _tableNamespace; private string _tablePrefix = string.Empty; - internal DataExpression _displayExpression; + internal DataExpression? _displayExpression; internal bool _fNestedInDataset = true; // globalization stuff private CultureInfo _culture; private bool _cultureUserSet; - private CompareInfo _compareInfo; + private CompareInfo? _compareInfo; private CompareOptions _compareFlags = CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth; - private IFormatProvider _formatProvider; - private StringComparer _hashCodeProvider; + private IFormatProvider? _formatProvider; + private StringComparer? _hashCodeProvider; private bool _caseSensitive; private bool _caseSensitiveUserSet; // XML properties - internal string _encodedTableName; // For XmlDataDocument only - internal DataColumn _xmlText; // text values of a complex xml element - internal DataColumn _colUnique; + internal string? _encodedTableName; // For XmlDataDocument only + internal DataColumn? _xmlText; // text values of a complex xml element + internal DataColumn? _colUnique; internal decimal _minOccurs = 1; // default = 1 internal decimal _maxOccurs = 1; // default = 1 internal bool _repeatableElement; - private object _typeName; + private object? _typeName; // primary key info - internal UniqueConstraint _primaryKey; + internal UniqueConstraint? _primaryKey; internal IndexField[] _primaryIndex = Array.Empty(); - private DataColumn[] _delayedSetPrimaryKey; + private DataColumn[]? _delayedSetPrimaryKey; // Loading Schema and/or Data related optimization - private Index _loadIndex; - private Index _loadIndexwithOriginalAdded; - private Index _loadIndexwithCurrentDeleted; + private Index? _loadIndex; + private Index? _loadIndexwithOriginalAdded; + private Index? _loadIndexwithCurrentDeleted; private int _suspendIndexEvents; private bool _savedEnforceConstraints; @@ -110,31 +111,31 @@ namespace System.Data internal bool _fInLoadDiffgram; private byte _isTypedDataTable; // 0 == unknown, 1 = yes, 2 = No - private DataRow[] _emptyDataRowArray; + private DataRow[]? _emptyDataRowArray; // Property Descriptor Cache for DataBinding - private PropertyDescriptorCollection _propertyDescriptorCollectionCache; + private PropertyDescriptorCollection? _propertyDescriptorCollectionCache; // Cache for relation that has this table as nested child table. private DataRelation[] _nestedParentRelations = Array.Empty(); // Dependent column list for expression evaluation - internal List _dependentColumns; + internal List? _dependentColumns; // events private bool _mergingData; - private DataRowChangeEventHandler _onRowChangedDelegate; - private DataRowChangeEventHandler _onRowChangingDelegate; - private DataRowChangeEventHandler _onRowDeletingDelegate; - private DataRowChangeEventHandler _onRowDeletedDelegate; - private DataColumnChangeEventHandler _onColumnChangedDelegate; - private DataColumnChangeEventHandler _onColumnChangingDelegate; - private DataTableClearEventHandler _onTableClearingDelegate; - private DataTableClearEventHandler _onTableClearedDelegate; - private DataTableNewRowEventHandler _onTableNewRowDelegate; - private PropertyChangedEventHandler _onPropertyChangingDelegate; - - private EventHandler _onInitialized; + private DataRowChangeEventHandler? _onRowChangedDelegate; + private DataRowChangeEventHandler? _onRowChangingDelegate; + private DataRowChangeEventHandler? _onRowDeletingDelegate; + private DataRowChangeEventHandler? _onRowDeletedDelegate; + private DataColumnChangeEventHandler? _onColumnChangedDelegate; + private DataColumnChangeEventHandler? _onColumnChangingDelegate; + private DataTableClearEventHandler? _onTableClearingDelegate; + private DataTableClearEventHandler? _onTableClearedDelegate; + private DataTableNewRowEventHandler? _onTableNewRowDelegate; + private PropertyChangedEventHandler? _onPropertyChangingDelegate; + + private EventHandler? _onInitialized; // misc private readonly DataRowBuilder _rowBuilder; @@ -144,7 +145,7 @@ namespace System.Data internal readonly List _delayedViews = new List(); private readonly List _dataViewListeners = new List(); - internal Hashtable _rowDiffId; + internal Hashtable? _rowDiffId; internal readonly ReaderWriterLockSlim _indexesLock = new ReaderWriterLockSlim(); internal int _ukColumnPositionForInference = -1; @@ -177,12 +178,12 @@ namespace System.Data /// Initializes a new instance of the class with the specified table /// name. /// - public DataTable(string tableName) : this() + public DataTable(string? tableName) : this() { _tableName = tableName == null ? "" : tableName; } - public DataTable(string tableName, string tableNamespace) : this(tableName) + public DataTable(string? tableName, string? tableNamespace) : this(tableName) { Namespace = tableNamespace; } @@ -198,7 +199,7 @@ namespace System.Data switch (e.Name) { case "DataTable.RemotingFormat": //DataTable.RemotingFormat does not exist in V1/V1.1 versions - remotingFormat = (SerializationFormat)e.Value; + remotingFormat = (SerializationFormat)e.Value!; break; } } @@ -258,11 +259,11 @@ namespace System.Data } else { - tempDSNamespace = DataSet.Namespace; - DataSet._namespaceURI = Namespace; + tempDSNamespace = _dataSet.Namespace; + _dataSet._namespaceURI = Namespace; } - info.AddValue(KEY_XMLSCHEMA, _dataSet.GetXmlSchemaForRemoting(this)); + info.AddValue(KEY_XMLSCHEMA, _dataSet!.GetXmlSchemaForRemoting(this)); info.AddValue(KEY_XMLDIFFGRAM, _dataSet.GetRemotingDiffGram(this)); if (fCreatedDataSet) @@ -292,8 +293,8 @@ namespace System.Data else { //XML/V1.0/V1.1 - string strSchema = (string)info.GetValue(KEY_XMLSCHEMA, typeof(string)); - string strData = (string)info.GetValue(KEY_XMLDIFFGRAM, typeof(string)); + string? strSchema = (string?)info.GetValue(KEY_XMLSCHEMA, typeof(string)); + string? strData = (string?)info.GetValue(KEY_XMLDIFFGRAM, typeof(string)); if (strSchema != null) { @@ -397,15 +398,15 @@ namespace System.Data internal void DeserializeTableSchema(SerializationInfo info, StreamingContext context, bool isSingleTable) { //DataTable basic properties - _tableName = info.GetString("DataTable.TableName"); + _tableName = info.GetString("DataTable.TableName")!; _tableNamespace = info.GetString("DataTable.Namespace"); - _tablePrefix = info.GetString("DataTable.Prefix"); + _tablePrefix = info.GetString("DataTable.Prefix")!; bool caseSensitive = info.GetBoolean("DataTable.CaseSensitive"); SetCaseSensitiveValue(caseSensitive, true, false); _caseSensitiveUserSet = !info.GetBoolean("DataTable.caseSensitiveAmbient"); - int lcid = (int)info.GetValue("DataTable.LocaleLCID", typeof(int)); + int lcid = (int)info.GetValue("DataTable.LocaleLCID", typeof(int))!; CultureInfo culture = new CultureInfo(lcid); SetLocaleValue(culture, true, false); _cultureUserSet = true; @@ -414,16 +415,16 @@ namespace System.Data //DataTable state internal properties _fNestedInDataset = info.GetBoolean("DataTable.NestedInDataSet"); - string tName = info.GetString("DataTable.TypeName"); + string tName = info.GetString("DataTable.TypeName")!; _typeName = new XmlQualifiedName(tName); _repeatableElement = info.GetBoolean("DataTable.RepeatableElement"); //ExtendedProperties - _extendedProperties = (PropertyCollection)info.GetValue("DataTable.ExtendedProperties", typeof(PropertyCollection)); + _extendedProperties = (PropertyCollection?)info.GetValue("DataTable.ExtendedProperties", typeof(PropertyCollection)); //Columns int colCount = info.GetInt32("DataTable.Columns.Count"); - string[] expressions = new string[colCount]; + string?[] expressions = new string?[colCount]; Debug.Assert(Columns.Count == 0, "There is column in Table"); IFormatProvider formatProvider = CultureInfo.InvariantCulture; @@ -436,13 +437,13 @@ namespace System.Data dc._columnUri = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.Namespace", i)); dc.Prefix = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.Prefix", i)); - string typeName = (string)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DataType_AssemblyQualifiedName", i), typeof(string)); + string typeName = (string)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DataType_AssemblyQualifiedName", i), typeof(string))!; dc.DataType = Type.GetType(typeName, throwOnError: true); - dc.XmlDataType = (string)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.XmlDataType", i), typeof(string)); - dc.SimpleType = (SimpleType)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.SimpleType", i), typeof(SimpleType)); + dc.XmlDataType = (string?)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.XmlDataType", i), typeof(string)); + dc.SimpleType = (SimpleType?)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.SimpleType", i), typeof(SimpleType)); - dc.ColumnMapping = (MappingType)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnMapping", i), typeof(MappingType)); - dc.DateTimeMode = (DataSetDateTime)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DateTimeMode", i), typeof(DataSetDateTime)); + dc.ColumnMapping = (MappingType)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnMapping", i), typeof(MappingType))!; + dc.DateTimeMode = (DataSetDateTime)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DateTimeMode", i), typeof(DataSetDateTime))!; dc.AllowDBNull = info.GetBoolean(string.Format(formatProvider, "DataTable.DataColumn_{0}.AllowDBNull", i)); dc.AutoIncrement = info.GetBoolean(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrement", i)); @@ -454,7 +455,7 @@ namespace System.Data dc.MaxLength = info.GetInt32(string.Format(formatProvider, "DataTable.DataColumn_{0}.MaxLength", i)); //DataColumn internal state properties - dc.AutoIncrementCurrent = info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementCurrent", i), typeof(object)); + dc.AutoIncrementCurrent = info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementCurrent", i), typeof(object))!; //Expression if (isSingleTable) @@ -463,7 +464,7 @@ namespace System.Data } //ExtendedProperties - dc._extendedProperties = (PropertyCollection)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ExtendedProperties", i), typeof(PropertyCollection)); + dc._extendedProperties = (PropertyCollection?)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ExtendedProperties", i), typeof(PropertyCollection)); Columns.Add(dc); } if (isSingleTable) @@ -502,7 +503,7 @@ namespace System.Data { Constraint c = Constraints[i]; - UniqueConstraint uc = c as UniqueConstraint; + UniqueConstraint? uc = c as UniqueConstraint; if (uc != null) { int[] colInfo = new int[uc.Columns.Length]; @@ -522,21 +523,21 @@ namespace System.Data } else { - ForeignKeyConstraint fk = c as ForeignKeyConstraint; + ForeignKeyConstraint? fk = c as ForeignKeyConstraint; Debug.Assert(fk != null); bool shouldSerialize = (allConstraints == true) || (fk.Table == this && fk.RelatedTable == this); if (shouldSerialize) { int[] parentInfo = new int[fk.RelatedColumns.Length + 1]; - parentInfo[0] = allConstraints ? DataSet.Tables.IndexOf(fk.RelatedTable) : 0; + parentInfo[0] = allConstraints ? DataSet!.Tables.IndexOf(fk.RelatedTable) : 0; for (int j = 1; j < parentInfo.Length; j++) { parentInfo[j] = fk.RelatedColumns[j - 1].Ordinal; } int[] childInfo = new int[fk.Columns.Length + 1]; - childInfo[0] = allConstraints ? DataSet.Tables.IndexOf(fk.Table) : 0; //Since the constraint is on the current table, this is the child table. + childInfo[0] = allConstraints ? DataSet!.Tables.IndexOf(fk.Table) : 0; //Since the constraint is on the current table, this is the child table. for (int j = 1; j < childInfo.Length; j++) { childInfo[j] = fk.Columns[j - 1].Ordinal; @@ -563,20 +564,20 @@ namespace System.Data // Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties] internal void DeserializeConstraints(SerializationInfo info, StreamingContext context, int serIndex, bool allConstraints) { - ArrayList constraintList = (ArrayList)info.GetValue(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), typeof(ArrayList)); + ArrayList constraintList = (ArrayList)info.GetValue(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), typeof(ArrayList))!; foreach (ArrayList list in constraintList) { - string con = (string)list[0]; + string con = (string)list[0]!; if (con.Equals("U")) { //Unique Constraints - string constraintName = (string)list[1]; + string constraintName = (string)list[1]!; - int[] keyColumnIndexes = (int[])list[2]; - bool isPrimaryKey = (bool)list[3]; - PropertyCollection extendedProperties = (PropertyCollection)list[4]; + int[] keyColumnIndexes = (int[])list[2]!; + bool isPrimaryKey = (bool)list[3]!; + PropertyCollection? extendedProperties = (PropertyCollection?)list[4]; DataColumn[] keyColumns = new DataColumn[keyColumnIndexes.Length]; for (int i = 0; i < keyColumnIndexes.Length; i++) @@ -596,14 +597,14 @@ namespace System.Data //ForeignKeyConstraints Debug.Assert(con.Equals("F")); - string constraintName = (string)list[1]; - int[] parentInfo = (int[])list[2]; - int[] childInfo = (int[])list[3]; - int[] rules = (int[])list[4]; - PropertyCollection extendedProperties = (PropertyCollection)list[5]; + string constraintName = (string)list[1]!; + int[] parentInfo = (int[])list[2]!; + int[] childInfo = (int[])list[3]!; + int[] rules = (int[])list[4]!; + PropertyCollection? extendedProperties = (PropertyCollection?)list[5]; //ParentKey Columns. - DataTable parentTable = (allConstraints == false) ? this : DataSet.Tables[parentInfo[0]]; + DataTable parentTable = (allConstraints == false) ? this : DataSet!.Tables[parentInfo[0]]; DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1]; for (int i = 0; i < parentkeyColumns.Length; i++) { @@ -611,7 +612,7 @@ namespace System.Data } //ChildKey Columns. - DataTable childTable = (allConstraints == false) ? this : DataSet.Tables[childInfo[0]]; + DataTable childTable = (allConstraints == false) ? this : DataSet!.Tables[childInfo[0]]; DataColumn[] childkeyColumns = new DataColumn[childInfo.Length - 1]; for (int i = 0; i < childkeyColumns.Length; i++) { @@ -647,7 +648,7 @@ namespace System.Data int colCount = Columns.Count; for (int i = 0; i < colCount; i++) { - string expr = info.GetString(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.DataColumn_{1}.Expression", serIndex, i)); + string expr = info.GetString(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.DataColumn_{1}.Expression", serIndex, i))!; if (0 != expr.Length) { Columns[i].Expression = expr; @@ -753,12 +754,12 @@ namespace System.Data IFormatProvider formatProvider = CultureInfo.InvariantCulture; int rowCount = info.GetInt32(string.Format(formatProvider, "DataTable_{0}.Rows.Count", serIndex)); int recordCount = info.GetInt32(string.Format(formatProvider, "DataTable_{0}.Records.Count", serIndex)); - BitArray rowStates = (BitArray)info.GetValue(string.Format(formatProvider, "DataTable_{0}.RowStates", serIndex), typeof(BitArray)); - ArrayList storeList = (ArrayList)info.GetValue(string.Format(formatProvider, "DataTable_{0}.Records", serIndex), typeof(ArrayList)); - ArrayList nullbitList = (ArrayList)info.GetValue(string.Format(formatProvider, "DataTable_{0}.NullBits", serIndex), typeof(ArrayList)); - Hashtable rowErrors = (Hashtable)info.GetValue(string.Format(formatProvider, "DataTable_{0}.RowErrors", serIndex), typeof(Hashtable)); + BitArray rowStates = (BitArray)info.GetValue(string.Format(formatProvider, "DataTable_{0}.RowStates", serIndex), typeof(BitArray))!; + ArrayList storeList = (ArrayList)info.GetValue(string.Format(formatProvider, "DataTable_{0}.Records", serIndex), typeof(ArrayList))!; + ArrayList nullbitList = (ArrayList)info.GetValue(string.Format(formatProvider, "DataTable_{0}.NullBits", serIndex), typeof(ArrayList))!; + Hashtable rowErrors = (Hashtable)info.GetValue(string.Format(formatProvider, "DataTable_{0}.RowErrors", serIndex), typeof(Hashtable))!; rowErrors.OnDeserialization(this); //OnDeSerialization must be called since the hashtable gets deserialized after the whole graph gets deserialized - Hashtable colErrors = (Hashtable)info.GetValue(string.Format(formatProvider, "DataTable_{0}.ColumnErrors", serIndex), typeof(Hashtable)); + Hashtable colErrors = (Hashtable)info.GetValue(string.Format(formatProvider, "DataTable_{0}.ColumnErrors", serIndex), typeof(Hashtable))!; colErrors.OnDeserialization(this); //OnDeSerialization must be called since the hashtable gets deserialized after the whole graph gets deserialized if (recordCount <= 0) @@ -770,7 +771,7 @@ namespace System.Data //Point the record manager storage to the deserialized values. for (int i = 0; i < Columns.Count; i++) { - Columns[i].SetStorage(storeList[i], (BitArray)nullbitList[i]); + Columns[i].SetStorage(storeList[i]!, (BitArray)nullbitList[i]!); } //Create rows and set the records appropriately. @@ -903,13 +904,13 @@ namespace System.Data if (rowErrors.ContainsKey(rowIndex)) { - row.RowError = (string)rowErrors[rowIndex]; + row.RowError = (string)rowErrors[rowIndex]!; } if (colErrors.ContainsKey(rowIndex)) { - ArrayList list = (ArrayList)colErrors[rowIndex]; - int[] columnsInError = (int[])list[0]; - string[] columnErrors = (string[])list[1]; + ArrayList list = (ArrayList)colErrors[rowIndex]!; + int[] columnsInError = (int[])list[0]!; + string[] columnErrors = (string[])list[1]!; Debug.Assert(columnsInError.Length == columnErrors.Length); for (int i = 0; i < columnsInError.Length; i++) { @@ -955,14 +956,14 @@ namespace System.Data _suspendIndexEvents--; if (0 == _suspendIndexEvents) { - Exception first = null; + Exception? first = null; SetShadowIndexes(); try { // the length of shadowIndexes will not change // but the array instance may change during // events during Index.Reset - int numIndexes = _shadowIndexes.Count; + int numIndexes = _shadowIndexes!.Count; for (int i = 0; i < numIndexes; i++) { Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy() @@ -1168,12 +1169,12 @@ namespace System.Data /// Gets the that this table belongs to. /// [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)] - public DataSet DataSet => _dataSet; + public DataSet? DataSet => _dataSet; /// /// Internal method for setting the DataSet pointer. /// - internal void SetDataSet(DataSet dataSet) + internal void SetDataSet(DataSet? dataSet) { if (_dataSet != dataSet) { @@ -1207,7 +1208,7 @@ namespace System.Data { get { - DataView view = _defaultView; + DataView? view = _defaultView; if (null == view) { if (null != _dataSet) @@ -1220,7 +1221,7 @@ namespace System.Data view.SetIndex2("", DataViewRowState.CurrentRows, null, true); } - view = Interlocked.CompareExchange(ref _defaultView, view, null); + view = Interlocked.CompareExchange(ref _defaultView, view, null); if (null == view) { view = _defaultView; @@ -1235,6 +1236,7 @@ namespace System.Data /// this table in UI. /// [DefaultValue("")] + [AllowNull] public string DisplayExpression { get { return DisplayExpressionInternal; } @@ -1547,7 +1549,7 @@ namespace System.Data private DataRelation[] FindNestedParentRelations() { - List nestedParents = null; + List? nestedParents = null; foreach (DataRelation relation in ParentRelations) { if (relation.Nested) @@ -1585,22 +1587,23 @@ namespace System.Data /// Gets or sets an array of columns that function as primary keys for the data table. /// [TypeConverter(typeof(PrimaryKeyTypeConverter))] + [AllowNull] public DataColumn[] PrimaryKey { get { - UniqueConstraint primayKeyConstraint = _primaryKey; + UniqueConstraint? primayKeyConstraint = _primaryKey; if (null != primayKeyConstraint) { - Debug.Assert(2 <= _primaryKey.ConstraintIndex.RefCount, "bad primaryKey index RefCount"); + Debug.Assert(2 <= primayKeyConstraint.ConstraintIndex.RefCount, "bad primaryKey index RefCount"); return primayKeyConstraint.Key.ToArray(); } return Array.Empty(); } set { - UniqueConstraint key = null; - UniqueConstraint existingKey = null; + UniqueConstraint? key = null; + UniqueConstraint? existingKey = null; // Loading with persisted property if (fInitInProgress && value != null) @@ -1647,13 +1650,13 @@ namespace System.Data } // Use an existing UniqueConstraint that matches if one exists - if ((existingKey = (UniqueConstraint)Constraints.FindConstraint(key)) != null) + if ((existingKey = (UniqueConstraint?)Constraints.FindConstraint(key)) != null) { - key.ColumnsReference.CopyTo(existingKey.Key.ColumnsReference, 0); + key!.ColumnsReference.CopyTo(existingKey.Key.ColumnsReference, 0); key = existingKey; } - UniqueConstraint oldKey = _primaryKey; + UniqueConstraint? oldKey = _primaryKey; _primaryKey = null; if (oldKey != null) { @@ -1686,13 +1689,13 @@ namespace System.Data _primaryKey = key; - Debug.Assert(Constraints.FindConstraint(_primaryKey) == _primaryKey, "PrimaryKey is not in ConstraintCollection"); + Debug.Assert(_primaryKey == null || Constraints.FindConstraint(_primaryKey) == _primaryKey, "PrimaryKey is not in ConstraintCollection"); _primaryIndex = (key != null) ? key.Key.GetIndexDesc() : Array.Empty(); if (_primaryKey != null) { // must set index for DataView.Sort before setting AllowDBNull which can fail - key.ConstraintIndex.AddRef(); + key!.ConstraintIndex.AddRef(); for (int i = 0; i < key.ColumnsReference.Length; i++) { @@ -1726,6 +1729,7 @@ namespace System.Data /// [RefreshProperties(RefreshProperties.All)] [DefaultValue("")] + [AllowNull] public string TableName { get { return _tableName; } @@ -1799,12 +1803,11 @@ namespace System.Data } } - internal string EncodedTableName { get { - string encodedTblName = _encodedTableName; + string? encodedTblName = _encodedTableName; if (null == encodedTblName) { encodedTblName = XmlConvert.EncodeLocalName(TableName); @@ -1813,6 +1816,7 @@ namespace System.Data return encodedTblName; } } + private string GetInheritedNamespace(List visitedTables) { // if there is nested relation: ie: this table is nested child of another table and @@ -1858,6 +1862,7 @@ namespace System.Data /// /// Gets or sets the namespace for the . /// + [AllowNull] public string Namespace { get { return _tableNamespace ?? GetInheritedNamespace(new List()); } @@ -1901,7 +1906,7 @@ namespace System.Data if ((rel.Nested) && (rel.ChildTable != this) && (rel.ChildTable._tableNamespace == null)) { DataTable childTable = rel.ChildTable; - if (_dataSet.Tables.Contains(childTable.TableName, realNamespace, false, true)) + if (_dataSet!.Tables.Contains(childTable.TableName, realNamespace, false, true)) throw ExceptionBuilder.DuplicateTableName2(TableName, realNamespace); childTable.CheckCascadingNamespaceConflict(realNamespace); @@ -1909,7 +1914,7 @@ namespace System.Data } } - internal void CheckNamespaceValidityForNestedRelations(string realNamespace) + internal void CheckNamespaceValidityForNestedRelations(string? realNamespace) { foreach (DataRelation rel in ChildRelations) { @@ -2021,6 +2026,7 @@ namespace System.Data } [DefaultValue("")] + [AllowNull] public string Prefix { get { return _tablePrefix; } @@ -2040,7 +2046,7 @@ namespace System.Data } } - internal DataColumn XmlText + internal DataColumn? XmlText { get { return _xmlText; } set @@ -2089,15 +2095,15 @@ namespace System.Data } } - internal DataRow FindByIndex(Index ndx, object[] key) + internal DataRow? FindByIndex(Index ndx, object[] key) { Range range = ndx.FindRecords(key); return range.IsNull ? null : _recordManager[ndx.GetRecord(range.Min)]; } - internal DataRow FindMergeTarget(DataRow row, DataKey key, Index ndx) + internal DataRow? FindMergeTarget(DataRow row, DataKey key, Index ndx) { - DataRow targetRow = null; + DataRow? targetRow = null; // Primary key match if (key.HasValue) @@ -2128,7 +2134,7 @@ namespace System.Data } } - internal DataRow MergeRow(DataRow row, DataRow targetRow, bool preserveChanges, Index idxSearch) + internal DataRow MergeRow(DataRow row, DataRow? targetRow, bool preserveChanges, Index? idxSearch) { if (targetRow == null) { @@ -2178,7 +2184,7 @@ namespace System.Data if (saveIdxRecord != ((saveRowState == DataRowState.Added) ? newRecord : oldRecord)) { SetMergeRecords(targetRow, newRecord, oldRecord, (newRecord == -1) ? DataRowAction.Delete : DataRowAction.Change); - idxSearch.Reset(); + idxSearch!.Reset(); saveIdxRecord = ((saveRowState == DataRowState.Added) ? newRecord : oldRecord); } else @@ -2206,7 +2212,7 @@ namespace System.Data if (saveRowState == DataRowState.Added && targetRow._oldRecord != -1) { - idxSearch.Reset(); + idxSearch!.Reset(); } Debug.Assert(saveIdxRecord == ((saveRowState == DataRowState.Added) ? targetRow._newRecord : targetRow._oldRecord), "oops, you change index record without noticing it"); @@ -2232,7 +2238,7 @@ namespace System.Data for (int i = 0; i < cols.Length; i++) { - DataColumn col = targetRow.Table.Columns[cols[i].ColumnName]; + DataColumn col = targetRow.Table.Columns[cols[i].ColumnName]!; targetRow.SetColumnError(col, row.GetColumnError(cols[i])); } } @@ -2284,11 +2290,11 @@ namespace System.Data // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set. [MethodImpl(MethodImplOptions.NoInlining)] - protected virtual DataTable CreateInstance() => (DataTable)Activator.CreateInstance(GetType(), true); + protected virtual DataTable CreateInstance() => (DataTable)Activator.CreateInstance(GetType(), true)!; public virtual DataTable Clone() => Clone(null); - internal DataTable Clone(DataSet cloneDS) + internal DataTable Clone(DataSet? cloneDS) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, cloneDS={1}", ObjectID, (cloneDS != null) ? cloneDS.ObjectID : 0); try @@ -2320,7 +2326,7 @@ namespace System.Data return targetTable; } - private DataTable CloneHierarchy(DataTable sourceTable, DataSet ds, Hashtable visitedMap) + private DataTable CloneHierarchy(DataTable sourceTable, DataSet ds, Hashtable? visitedMap) { if (visitedMap == null) { @@ -2328,10 +2334,10 @@ namespace System.Data } if (visitedMap.Contains(sourceTable)) { - return ((DataTable)visitedMap[sourceTable]); + return ((DataTable)visitedMap[sourceTable]!); } - DataTable destinationTable = ds.Tables[sourceTable.TableName, sourceTable.Namespace]; + DataTable? destinationTable = ds.Tables[sourceTable.TableName, sourceTable.Namespace]; if ((destinationTable != null && destinationTable.Columns.Count > 0)) { @@ -2359,7 +2365,7 @@ namespace System.Data return destinationTable; } - private DataTable CloneTo(DataTable clone, DataSet cloneDS, bool skipExpressionColumns) + private DataTable CloneTo(DataTable clone, DataSet? cloneDS, bool skipExpressionColumns) { // we do clone datatables while we do readxmlschema, so we do not want to clone columnexpressions if we call this from ReadXmlSchema // it will cause exception to be thrown in cae expression refers to a table that is not in hirerachy or not created yet @@ -2399,7 +2405,7 @@ namespace System.Data { for (int i = 0; i < clmns.Count; i++) { - clone.Columns[clmns[i].ColumnName].Expression = clmns[i].Expression; + clone.Columns[clmns[i].ColumnName]!.Expression = clmns[i].Expression; } } @@ -2419,15 +2425,14 @@ namespace System.Data // Rename first for (int j = 0; j < Constraints.Count; j++) { - ForeignKeyConstraint foreign = Constraints[j] as ForeignKeyConstraint; - UniqueConstraint unique = Constraints[j] as UniqueConstraint; + ForeignKeyConstraint? foreign = Constraints[j] as ForeignKeyConstraint; + UniqueConstraint? unique = Constraints[j] as UniqueConstraint; if (foreign != null) { if (foreign.Table == foreign.RelatedTable) { - ForeignKeyConstraint clonedConstraint = foreign.Clone(clone); - Constraint oldConstraint = clone.Constraints.FindConstraint(clonedConstraint); - if (oldConstraint != null) + if (foreign.Clone(clone) is { } clonedConstraint && + clone.Constraints.FindConstraint(clonedConstraint) is { } oldConstraint) { oldConstraint.ConstraintName = Constraints[j].ConstraintName; } @@ -2435,9 +2440,8 @@ namespace System.Data } else if (unique != null) { - UniqueConstraint clonedConstraint = unique.Clone(clone); - Constraint oldConstraint = clone.Constraints.FindConstraint(clonedConstraint); - if (oldConstraint != null) + if (unique.Clone(clone) is { } clonedConstraint && + clone.Constraints.FindConstraint(clonedConstraint) is { } oldConstraint) { oldConstraint.ConstraintName = Constraints[j].ConstraintName; foreach (object key in clonedConstraint.ExtendedProperties.Keys) @@ -2453,22 +2457,20 @@ namespace System.Data { if (!clone.Constraints.Contains(Constraints[j].ConstraintName, true)) { - ForeignKeyConstraint foreign = Constraints[j] as ForeignKeyConstraint; - UniqueConstraint unique = Constraints[j] as UniqueConstraint; + ForeignKeyConstraint? foreign = Constraints[j] as ForeignKeyConstraint; + UniqueConstraint? unique = Constraints[j] as UniqueConstraint; if (foreign != null) { - if (foreign.Table == foreign.RelatedTable) + if (foreign.Table == foreign.RelatedTable && + foreign.Clone(clone) is { } newforeign) { - ForeignKeyConstraint newforeign = foreign.Clone(clone); - if (newforeign != null) - { // we cant make sure that we recieve a cloned FKC,since it depends if table and relatedtable be the same - clone.Constraints.Add(newforeign); - } + // we cant make sure that we recieve a cloned FKC,since it depends if table and relatedtable be the same + clone.Constraints.Add(newforeign); } } else if (unique != null) { - clone.Constraints.Add(unique.Clone(clone)); + clone.Constraints.Add(unique.Clone(clone)!); } } } @@ -2509,7 +2511,7 @@ namespace System.Data /// /// Occurs when a value has been submitted for this column. /// - public event DataColumnChangeEventHandler ColumnChanging + public event DataColumnChangeEventHandler? ColumnChanging { add { @@ -2523,7 +2525,7 @@ namespace System.Data } } - public event DataColumnChangeEventHandler ColumnChanged + public event DataColumnChangeEventHandler? ColumnChanged { add { @@ -2537,7 +2539,7 @@ namespace System.Data } } - public event EventHandler Initialized + public event EventHandler? Initialized { add { _onInitialized += value; } remove { _onInitialized -= value; } @@ -2560,7 +2562,7 @@ namespace System.Data /// /// Occurs after a row in the table has been successfully edited. /// - public event DataRowChangeEventHandler RowChanged + public event DataRowChangeEventHandler? RowChanged { add { @@ -2577,7 +2579,7 @@ namespace System.Data /// /// Occurs when the is changing. /// - public event DataRowChangeEventHandler RowChanging + public event DataRowChangeEventHandler? RowChanging { add { @@ -2594,7 +2596,7 @@ namespace System.Data /// /// Occurs before a row in the table is about to be deleted. /// - public event DataRowChangeEventHandler RowDeleting + public event DataRowChangeEventHandler? RowDeleting { add { @@ -2611,7 +2613,7 @@ namespace System.Data /// /// Occurs after a row in the table has been deleted. /// - public event DataRowChangeEventHandler RowDeleted + public event DataRowChangeEventHandler? RowDeleted { add { @@ -2625,7 +2627,7 @@ namespace System.Data } } - public event DataTableClearEventHandler TableClearing + public event DataTableClearEventHandler? TableClearing { add { @@ -2639,7 +2641,7 @@ namespace System.Data } } - public event DataTableClearEventHandler TableCleared + public event DataTableClearEventHandler? TableCleared { add { @@ -2653,7 +2655,7 @@ namespace System.Data } } - public event DataTableNewRowEventHandler TableNewRow + public event DataTableNewRowEventHandler? TableNewRow { add { @@ -2665,6 +2667,8 @@ namespace System.Data } } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override ISite Site { @@ -2690,6 +2694,7 @@ namespace System.Data base.Site = value; } } +#nullable enable internal DataRow AddRecords(int oldRecord, int newRecord) { @@ -2717,7 +2722,7 @@ namespace System.Data internal void InsertRow(DataRow row, long proposedID, int pos, bool fireEvent) { - Exception deferredException = null; + Exception? deferredException = null; if (row == null) { @@ -2817,7 +2822,7 @@ namespace System.Data _dataSet.OnClearFunctionCalled(this); bool shouldFireClearEvents = (Rows.Count != 0); // if Rows is already empty, this is noop - DataTableClearEventArgs e = null; + DataTableClearEventArgs? e = null; if (shouldFireClearEvents) { e = new DataTableClearEventArgs(this); @@ -2850,7 +2855,7 @@ namespace System.Data if (shouldFireClearEvents) { - OnTableCleared(e); + OnTableCleared(e!); } foreach (DataColumn column in Columns) @@ -2866,7 +2871,7 @@ namespace System.Data internal void CascadeAll(DataRow row, DataRowAction action) { - if (DataSet != null && DataSet._fEnableCascading) + if (_dataSet != null && _dataSet._fEnableCascading) { for (ParentForeignKeyConstraintEnumerator constraints = new ParentForeignKeyConstraintEnumerator(_dataSet, this); constraints.GetNext();) { @@ -2878,7 +2883,7 @@ namespace System.Data internal void CommitRow(DataRow row) { // Fire Changing event - DataRowChangeEventArgs drcevent = OnRowChanging(null, row, DataRowAction.Commit); + DataRowChangeEventArgs? drcevent = OnRowChanging(null, row, DataRowAction.Commit); if (!_inDataLoad) { @@ -2892,7 +2897,7 @@ namespace System.Data internal int Compare(string s1, string s2) => Compare(s1, s2, null); - internal int Compare(string s1, string s2, CompareInfo comparer) + internal int Compare(string s1, string s2, CompareInfo? comparer) { object obj1 = s1; object obj2 = s2; @@ -2937,7 +2942,7 @@ namespace System.Data /// /// Computes the given expression on the current rows that pass the filter criteria. /// - public object Compute(string expression, string filter) + public object Compute(string? expression, string? filter) { DataRow[] rows = Select(filter, "", DataViewRowState.CurrentRows); DataExpression expr = new DataExpression(this, expression); @@ -2981,7 +2986,7 @@ namespace System.Data for (int i = 0; i < cols.Length; i++) { - DataColumn col = targetRow.Table.Columns[cols[i].ColumnName]; + DataColumn col = targetRow.Table.Columns[cols[i].ColumnName]!; targetRow.SetColumnError(col, row.GetColumnError(cols[i])); } } @@ -3003,19 +3008,19 @@ namespace System.Data if (_primaryKey == null) throw ExceptionBuilder.TableMissingPrimaryKey(); } - internal DataRow FindByPrimaryKey(object[] values) + internal DataRow? FindByPrimaryKey(object?[] values) { CheckPrimaryKey(); - return FindRow(_primaryKey.Key, values); + return FindRow(_primaryKey!.Key, values); } - internal DataRow FindByPrimaryKey(object value) + internal DataRow? FindByPrimaryKey(object? value) { CheckPrimaryKey(); - return FindRow(_primaryKey.Key, value); + return FindRow(_primaryKey!.Key, value); } - private DataRow FindRow(DataKey key, object[] values) + private DataRow? FindRow(DataKey key, object?[] values) { Index index = GetIndex(NewIndexDesc(key)); Range range = index.FindRecords(values); @@ -3026,7 +3031,7 @@ namespace System.Data return _recordManager[index.GetRecord(range.Min)]; } - private DataRow FindRow(DataKey key, object value) + private DataRow? FindRow(DataKey key, object? value) { Index index = GetIndex(NewIndexDesc(key)); Range range = index.FindRecords(value); @@ -3060,13 +3065,13 @@ namespace System.Data _recordManager.FreeRecord(ref record); } - public DataTable GetChanges() + public DataTable? GetChanges() { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { DataTable dtChanges = Clone(); - DataRow row = null; + DataRow? row = null; for (int i = 0; i < Rows.Count; i++) { @@ -3090,13 +3095,13 @@ namespace System.Data } } - public DataTable GetChanges(DataRowState rowStates) + public DataTable? GetChanges(DataRowState rowStates) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, rowStates={1}", ObjectID, rowStates); try { DataTable dtChanges = Clone(); - DataRow row = null; + DataRow? row = null; // check that rowStates is valid DataRowState Debug.Assert(Enum.GetUnderlyingType(typeof(DataRowState)) == typeof(int), "Invalid DataRowState type"); @@ -3147,10 +3152,10 @@ namespace System.Data internal Index GetIndex(IndexField[] indexDesc) => GetIndex(indexDesc, DataViewRowState.CurrentRows, null); - internal Index GetIndex(string sort, DataViewRowState recordStates, IFilter rowFilter) => + internal Index GetIndex(string sort, DataViewRowState recordStates, IFilter? rowFilter) => GetIndex(ParseSortString(sort), recordStates, rowFilter); - internal Index GetIndex(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) + internal Index GetIndex(IndexField[] indexDesc, DataViewRowState recordStates, IFilter? rowFilter) { _indexesLock.EnterUpgradeableReadLock(); try @@ -3176,9 +3181,12 @@ namespace System.Data return ndx; } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable IList IListSource.GetList() => DefaultView; internal List GetListeners() => _dataViewListeners; +#nullable enable // We need a HashCodeProvider for Case, Kana and Width insensitive internal int GetSpecialHashCode(string name) @@ -3201,7 +3209,7 @@ namespace System.Data } } - public void ImportRow(DataRow row) + public void ImportRow(DataRow? row) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try @@ -3241,7 +3249,7 @@ namespace System.Data for (int i = 0; i < cols.Length; i++) { - DataColumn col = targetRow.Table.Columns[cols[i].ColumnName]; + DataColumn col = targetRow.Table.Columns[cols[i].ColumnName]!; targetRow.SetColumnError(col, row.GetColumnError(cols[i])); } } @@ -3282,7 +3290,7 @@ namespace System.Data _nextRowID = checked(proposedID + 1); } - DataRowChangeEventArgs drcevent = null; + DataRowChangeEventArgs? drcevent = null; if (row._newRecord != -1) { @@ -3355,7 +3363,7 @@ namespace System.Data return _recordManager.NewRecordBase(); } - internal int NewRecordFromArray(object[] value) + internal int NewRecordFromArray(object?[] value) { int colCount = _columnCollection.Count; // Perf: use the readonly columnCollection field directly if (colCount < value.Length) @@ -3367,9 +3375,9 @@ namespace System.Data { for (int i = 0; i < value.Length; i++) { - if (null != value[i]) + if (value[i] is { } v) { - _columnCollection[i][record] = value[i]; + _columnCollection[i][record] = v; } else { @@ -3415,10 +3423,7 @@ namespace System.Data { _rowBuilder._record = -1; DataRow dr = NewRowFromBuilder(_rowBuilder); - if (_dataSet != null) - { - DataSet.OnDataRowCreated(dr); - } + _dataSet?.OnDataRowCreated(dr); return dr; } @@ -3484,10 +3489,7 @@ namespace System.Data DataRow row = NewRowFromBuilder(_rowBuilder); _recordManager[record] = row; - if (_dataSet != null) - { - DataSet.OnDataRowCreated(row); - } + _dataSet?.OnDataRowCreated(row); return row; } @@ -3563,7 +3565,7 @@ namespace System.Data /// protected virtual void OnRemoveColumn(DataColumn column) { } - private DataRowChangeEventArgs OnRowChanged(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) + private DataRowChangeEventArgs? OnRowChanged(DataRowChangeEventArgs? args, DataRow eRow, DataRowAction eAction) { if ((null != _onRowChangedDelegate) || IsTypedDataTable) { @@ -3576,7 +3578,7 @@ namespace System.Data return args; } - private DataRowChangeEventArgs OnRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) + private DataRowChangeEventArgs? OnRowChanging(DataRowChangeEventArgs? args, DataRow eRow, DataRowAction eAction) { if ((null != _onRowChangingDelegate) || IsTypedDataTable) { @@ -3677,7 +3679,7 @@ namespace System.Data } } - internal IndexField[] ParseSortString(string sortString) + internal IndexField[] ParseSortString(string? sortString) { IndexField[] indexDesc = Array.Empty(); if ((null != sortString) && (0 < sortString.Length)) @@ -3716,7 +3718,7 @@ namespace System.Data } // find the column. - DataColumn column = Columns[current]; + DataColumn? column = Columns[current]; if (column == null) { throw ExceptionBuilder.ColumnOutOfRange(current); @@ -3740,7 +3742,7 @@ namespace System.Data SetShadowIndexes(); // how about new assert? try { - int numIndexes = _shadowIndexes.Count; + int numIndexes = _shadowIndexes!.Count; for (int i = 0; i < numIndexes; i++) { Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy() @@ -3763,7 +3765,7 @@ namespace System.Data { SetShadowIndexes(); Debug.Assert(oldIndex.Length == newIndex.Length, "Size oldIndexes and newIndexes should be the same"); - Debug.Assert(oldIndex.Length == _shadowIndexes.Count, "Size of OldIndexes should be the same as size of Live indexes"); + Debug.Assert(oldIndex.Length == _shadowIndexes!.Count, "Size of OldIndexes should be the same as size of Live indexes"); try { int numIndexes = _shadowIndexes.Count; @@ -3787,7 +3789,7 @@ namespace System.Data SetShadowIndexes(); try { - int numIndexes = _shadowIndexes.Count; + int numIndexes = _shadowIndexes!.Count; for (int i = 0; i < numIndexes; i++) { Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy() @@ -3810,7 +3812,7 @@ namespace System.Data SetShadowIndexes(); try { - int numIndexes = _shadowIndexes.Count; + int numIndexes = _shadowIndexes!.Count; for (int i = 0; i < numIndexes; i++) { Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy() @@ -3931,7 +3933,7 @@ namespace System.Data } if (dc._dependentColumns != null) { - dc.Table.EvaluateDependentExpressions(dc._dependentColumns, dr, version, null); + dc.Table!.EvaluateDependentExpressions(dc._dependentColumns, dr, version, null); } } } @@ -4035,7 +4037,7 @@ namespace System.Data internal void ResetIndexes() => ResetInternalIndexes(null); - internal void ResetInternalIndexes(DataColumn column) + internal void ResetInternalIndexes(DataColumn? column) { Debug.Assert(null != _indexes, "unexpected null indexes"); SetShadowIndexes(); @@ -4044,7 +4046,7 @@ namespace System.Data // the length of shadowIndexes will not change // but the array instance may change during // events during Index.Reset - int numIndexes = _shadowIndexes.Count; + int numIndexes = _shadowIndexes!.Count; for (int i = 0; i < numIndexes; i++) { Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy() @@ -4085,7 +4087,7 @@ namespace System.Data SetNewRecord(row, row._oldRecord, DataRowAction.Rollback, false, true); } - private DataRowChangeEventArgs RaiseRowChanged(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) + private DataRowChangeEventArgs? RaiseRowChanged(DataRowChangeEventArgs? args, DataRow eRow, DataRowAction eAction) { try { @@ -4110,7 +4112,7 @@ namespace System.Data return args; } - private DataRowChangeEventArgs RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction) + private DataRowChangeEventArgs? RaiseRowChanging(DataRowChangeEventArgs? args, DataRow eRow, DataRowAction eAction) { if (UpdatingCurrent(eRow, eAction) && (IsTypedDataTable || (null != _onRowChangingDelegate))) { @@ -4147,7 +4149,7 @@ namespace System.Data return args; } - private DataRowChangeEventArgs RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction, bool fireEvent) + private DataRowChangeEventArgs? RaiseRowChanging(DataRowChangeEventArgs? args, DataRow eRow, DataRowAction eAction, bool fireEvent) { // check all constraints if (EnforceConstraints) @@ -4198,7 +4200,7 @@ namespace System.Data /// Returns an array of all objects that match the filter criteria in order of /// primary key (or lacking one, order of addition.) /// - public DataRow[] Select(string filterExpression) + public DataRow[] Select(string? filterExpression) { DataCommonEventSource.Log.Trace(" {0}, filterExpression='{1}'", ObjectID, filterExpression); return new Select(this, filterExpression, "", DataViewRowState.CurrentRows).SelectRows(); @@ -4208,7 +4210,7 @@ namespace System.Data /// Returns an array of all objects that match the filter criteria, in the /// specified sort order. /// - public DataRow[] Select(string filterExpression, string sort) + public DataRow[] Select(string? filterExpression, string? sort) { DataCommonEventSource.Log.Trace(" {0}, filterExpression='{1}', sort='{2}'", ObjectID, filterExpression, sort); return new Select(this, filterExpression, sort, DataViewRowState.CurrentRows).SelectRows(); @@ -4218,7 +4220,7 @@ namespace System.Data /// Returns an array of all objects that match the filter in the order of the /// sort, that match the specified state. /// - public DataRow[] Select(string filterExpression, string sort, DataViewRowState recordStates) + public DataRow[] Select(string? filterExpression, string? sort, DataViewRowState recordStates) { DataCommonEventSource.Log.Trace(" {0}, filterExpression='{1}', sort='{2}', recordStates={3}", ObjectID, filterExpression, sort, recordStates); return new Select(this, filterExpression, sort, recordStates).SelectRows(); @@ -4226,7 +4228,7 @@ namespace System.Data internal void SetNewRecord(DataRow row, int proposedRecord, DataRowAction action = DataRowAction.Change, bool isInMerge = false, bool fireEvent = true, bool suppressEnsurePropertyChanged = false) { - Exception deferredException = null; + Exception? deferredException = null; SetNewRecordWorker(row, proposedRecord, action, isInMerge, suppressEnsurePropertyChanged, -1, fireEvent, out deferredException); // we are going to call below overload from insert if (deferredException != null) { @@ -4235,7 +4237,7 @@ namespace System.Data } private void SetNewRecordWorker(DataRow row, int proposedRecord, DataRowAction action, bool isInMerge, bool suppressEnsurePropertyChanged, - int position, bool fireEvent, out Exception deferredException) + int position, bool fireEvent, out Exception? deferredException) { // this is the event workhorse... it will throw the changing/changed events // and update the indexes. Used by change, add, delete, revert. @@ -4276,7 +4278,7 @@ namespace System.Data row._tempRecord = proposedRecord; } - DataRowChangeEventArgs drcevent = null; + DataRowChangeEventArgs? drcevent = null; try { @@ -4317,7 +4319,7 @@ namespace System.Data } } - List cachedRows = null; + List? cachedRows = null; if ((action == DataRowAction.Delete || action == DataRowAction.Change) && _dependentColumns != null && _dependentColumns.Count > 0) { @@ -4662,7 +4664,7 @@ namespace System.Data /// Finds and updates a specific row. If no matching /// row is found, a new row is created using the given values. /// - public DataRow LoadDataRow(object[] values, bool fAcceptChanges) + public DataRow LoadDataRow(object?[] values, bool fAcceptChanges) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, fAcceptChanges={1}", ObjectID, fAcceptChanges); try @@ -4680,7 +4682,7 @@ namespace System.Data if (result != -1) { int resultRecord = _loadIndex.GetRecord(result); - row = _recordManager[resultRecord]; + row = _recordManager[resultRecord]!; Debug.Assert(row != null, "Row can't be null for index record"); row.CancelEdit(); if (row.RowState == DataRowState.Deleted) @@ -4723,12 +4725,12 @@ namespace System.Data /// /// Finds and updates a specific row. If no matching row is found, a new row is created using the given values. /// - public DataRow LoadDataRow(object[] values, LoadOption loadOption) + public DataRow LoadDataRow(object?[] values, LoadOption loadOption) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, loadOption={1}", ObjectID, loadOption); try { - Index indextoUse = null; + Index? indextoUse = null; if (_primaryKey != null) { if (loadOption == LoadOption.Upsert) @@ -4760,7 +4762,7 @@ namespace System.Data indextoUse = _loadIndexwithOriginalAdded; } // not expecting LiveIndexes to clear the index we use between calls to LoadDataRow - Debug.Assert(2 <= indextoUse.RefCount, "bad indextoUse.RefCount"); + Debug.Assert(2 <= indextoUse!.RefCount, "bad indextoUse.RefCount"); } if (_inDataLoad && !AreIndexEventsSuspended) { @@ -4779,9 +4781,9 @@ namespace System.Data } } - internal DataRow UpdatingAdd(object[] values) + internal DataRow UpdatingAdd(object?[] values) { - Index index = null; + Index? index = null; if (_primaryKey != null) { index = _primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows); @@ -4794,7 +4796,7 @@ namespace System.Data if (result != -1) { int resultRecord = index.GetRecord(result); - DataRow row = _recordManager[resultRecord]; + DataRow row = _recordManager[resultRecord]!; Debug.Assert(row != null, "Row can't be null for index record"); row.RejectChanges(); SetNewRecord(row, record); @@ -4885,7 +4887,7 @@ namespace System.Data /// additional properties. The returned array of properties will be /// filtered by the given set of attributes. /// - internal PropertyDescriptorCollection GetPropertyDescriptorCollection(Attribute[] attributes) + internal PropertyDescriptorCollection GetPropertyDescriptorCollection(Attribute[]? attributes) { if (_propertyDescriptorCollectionCache == null) { @@ -4952,14 +4954,14 @@ namespace System.Data public void Load(IDataReader reader, LoadOption loadOption) => Load(reader, loadOption, null); - public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler errorHandler) + public virtual void Load(IDataReader reader, LoadOption loadOption, FillErrorEventHandler? errorHandler) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, loadOption={1}", ObjectID, loadOption); try { if (PrimaryKey.Length == 0) { - DataTableReader dtReader = reader as DataTableReader; + DataTableReader? dtReader = reader as DataTableReader; if (dtReader != null && dtReader.CurrentDataTable == this) { return; // if not return, it will go to infinite loop @@ -4985,10 +4987,10 @@ namespace System.Data } } - private DataRow LoadRow(object[] values, LoadOption loadOption, Index searchIndex) + private DataRow LoadRow(object?[] values, LoadOption loadOption, Index? searchIndex) { int recordNo; - DataRow dataRow = null; + DataRow? dataRow = null; if (searchIndex != null) { @@ -5006,18 +5008,20 @@ namespace System.Data object[] keys = new object[primaryKeyIndex.Length]; for (int i = 0; i < primaryKeyIndex.Length; i++) { - keys[i] = values[primaryKeyIndex[i]]; + // TODO: There may be null values in the key + keys[i] = values[primaryKeyIndex[i]]!; } Range result = searchIndex.FindRecords(keys); if (!result.IsNull) { + Debug.Assert(result.Max >= result.Min); int deletedRowUpsertCount = 0; for (int i = result.Min; i <= result.Max; i++) { int resultRecord = searchIndex.GetRecord(i); - dataRow = _recordManager[resultRecord]; + dataRow = _recordManager[resultRecord]!; recordNo = NewRecordFromArray(values); // values array is being reused by DataAdapter, do not modify the values array @@ -5044,7 +5048,7 @@ namespace System.Data } if (0 == deletedRowUpsertCount) { - return dataRow; + return dataRow!; } } } @@ -5054,7 +5058,7 @@ namespace System.Data // fire rowChanging event here DataRowAction action; - DataRowChangeEventArgs drcevent = null; + DataRowChangeEventArgs? drcevent = null; switch (loadOption) { case LoadOption.OverwriteChanges: @@ -5116,7 +5120,7 @@ namespace System.Data } // No Event should be fired in SenNewRecord and SetOldRecord // fire rowChanging event here - DataRowChangeEventArgs drcevent = null; + DataRowChangeEventArgs? drcevent = null; DataRowAction action = DataRowAction.Nothing; int cacheTempRecord = dataRow._tempRecord; dataRow._tempRecord = recordNo; @@ -5290,25 +5294,25 @@ namespace System.Data public DataTableReader CreateDataReader() => new DataTableReader(this); - public void WriteXml(Stream stream) => WriteXml(stream, XmlWriteMode.IgnoreSchema, false); + public void WriteXml(Stream? stream) => WriteXml(stream, XmlWriteMode.IgnoreSchema, false); - public void WriteXml(Stream stream, bool writeHierarchy) => WriteXml(stream, XmlWriteMode.IgnoreSchema, writeHierarchy); + public void WriteXml(Stream? stream, bool writeHierarchy) => WriteXml(stream, XmlWriteMode.IgnoreSchema, writeHierarchy); - public void WriteXml(TextWriter writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema, false); + public void WriteXml(TextWriter? writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema, false); - public void WriteXml(TextWriter writer, bool writeHierarchy) => WriteXml(writer, XmlWriteMode.IgnoreSchema, writeHierarchy); + public void WriteXml(TextWriter? writer, bool writeHierarchy) => WriteXml(writer, XmlWriteMode.IgnoreSchema, writeHierarchy); - public void WriteXml(XmlWriter writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema, false); + public void WriteXml(XmlWriter? writer) => WriteXml(writer, XmlWriteMode.IgnoreSchema, false); - public void WriteXml(XmlWriter writer, bool writeHierarchy) => WriteXml(writer, XmlWriteMode.IgnoreSchema, writeHierarchy); + public void WriteXml(XmlWriter? writer, bool writeHierarchy) => WriteXml(writer, XmlWriteMode.IgnoreSchema, writeHierarchy); public void WriteXml(string fileName) => WriteXml(fileName, XmlWriteMode.IgnoreSchema, false); public void WriteXml(string fileName, bool writeHierarchy) => WriteXml(fileName, XmlWriteMode.IgnoreSchema, writeHierarchy); - public void WriteXml(Stream stream, XmlWriteMode mode) => WriteXml(stream, mode, false); + public void WriteXml(Stream? stream, XmlWriteMode mode) => WriteXml(stream, mode, false); - public void WriteXml(Stream stream, XmlWriteMode mode, bool writeHierarchy) + public void WriteXml(Stream? stream, XmlWriteMode mode, bool writeHierarchy) { if (stream != null) { @@ -5319,12 +5323,12 @@ namespace System.Data } } - public void WriteXml(TextWriter writer, XmlWriteMode mode) + public void WriteXml(TextWriter? writer, XmlWriteMode mode) { WriteXml(writer, mode, false); } - public void WriteXml(TextWriter writer, XmlWriteMode mode, bool writeHierarchy) + public void WriteXml(TextWriter? writer, XmlWriteMode mode, bool writeHierarchy) { if (writer != null) { @@ -5335,11 +5339,11 @@ namespace System.Data } } - public void WriteXml(XmlWriter writer, XmlWriteMode mode) + public void WriteXml(XmlWriter? writer, XmlWriteMode mode) { WriteXml(writer, mode, false); } - public void WriteXml(XmlWriter writer, XmlWriteMode mode, bool writeHierarchy) + public void WriteXml(XmlWriter? writer, XmlWriteMode mode, bool writeHierarchy) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, mode={1}", ObjectID, mode); try @@ -5361,8 +5365,8 @@ namespace System.Data // Create and save xml data if (mode == XmlWriteMode.WriteSchema) { - DataSet ds = null; - string tablenamespace = _tableNamespace; + DataSet? ds = null; + string? tablenamespace = _tableNamespace; if (null == DataSet) { ds = new DataSet(); @@ -5429,9 +5433,9 @@ namespace System.Data } } - public void WriteXmlSchema(Stream stream) => WriteXmlSchema(stream, false); + public void WriteXmlSchema(Stream? stream) => WriteXmlSchema(stream, false); - public void WriteXmlSchema(Stream stream, bool writeHierarchy) + public void WriteXmlSchema(Stream? stream, bool writeHierarchy) { if (stream == null) { @@ -5444,9 +5448,9 @@ namespace System.Data WriteXmlSchema(w, writeHierarchy); } - public void WriteXmlSchema(TextWriter writer) => WriteXmlSchema(writer, false); + public void WriteXmlSchema(TextWriter? writer) => WriteXmlSchema(writer, false); - public void WriteXmlSchema(TextWriter writer, bool writeHierarchy) + public void WriteXmlSchema(TextWriter? writer, bool writeHierarchy) { if (writer == null) { @@ -5480,10 +5484,10 @@ namespace System.Data { if (dc.Expression.Length != 0) { - DataColumn[] dependency = dc.DataExpression.GetDependency(); + DataColumn[] dependency = dc.DataExpression!.GetDependency(); for (int j = 0; j < dependency.Length; j++) { - if (!(tableList.Contains(dependency[j].Table))) + if (!(tableList.Contains(dependency[j].Table!))) { return false; } @@ -5494,9 +5498,9 @@ namespace System.Data return true; } - public void WriteXmlSchema(XmlWriter writer) => WriteXmlSchema(writer, false); + public void WriteXmlSchema(XmlWriter? writer) => WriteXmlSchema(writer, false); - public void WriteXmlSchema(XmlWriter writer, bool writeHierarchy) + public void WriteXmlSchema(XmlWriter? writer, bool writeHierarchy) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try @@ -5511,8 +5515,8 @@ namespace System.Data throw ExceptionBuilder.CanNotSerializeDataTableHierarchy(); } - DataSet ds = null; - string tablenamespace = _tableNamespace; //SQL BU Defect Tracking 286968 + DataSet? ds = null; + string? tablenamespace = _tableNamespace; //SQL BU Defect Tracking 286968 // Generate SchemaTree and write it out if (null == DataSet) @@ -5567,7 +5571,7 @@ namespace System.Data } } - public XmlReadMode ReadXml(Stream stream) + public XmlReadMode ReadXml(Stream? stream) { if (stream == null) { @@ -5582,7 +5586,7 @@ namespace System.Data return ReadXml(xr, false); } - public XmlReadMode ReadXml(TextReader reader) + public XmlReadMode ReadXml(TextReader? reader) { if (reader == null) { @@ -5614,7 +5618,7 @@ namespace System.Data } } - public XmlReadMode ReadXml(XmlReader reader) => ReadXml(reader, false); + public XmlReadMode ReadXml(XmlReader? reader) => ReadXml(reader, false); private void RestoreConstraint(bool originalEnforceConstraint) { @@ -5651,7 +5655,7 @@ namespace System.Data return false; } - internal XmlReadMode ReadXml(XmlReader reader, bool denyResolving) + internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, denyResolving={1}", ObjectID, denyResolving); try @@ -5692,7 +5696,7 @@ namespace System.Data } XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema - XmlDataLoader xmlload = null; + XmlDataLoader? xmlload = null; reader.MoveToContent(); if (Columns.Count == 0) @@ -5894,7 +5898,7 @@ namespace System.Data } } - internal XmlReadMode ReadXml(XmlReader reader, XmlReadMode mode, bool denyResolving) + internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResolving) { RowDiffIdUsageSection rowDiffIdUsage = default; try @@ -5945,11 +5949,11 @@ namespace System.Data } } - XmlDataLoader xmlload = null; + XmlDataLoader? xmlload = null; if (reader.NodeType == XmlNodeType.Element) { - XmlElement topNode = null; + XmlElement? topNode = null; if (mode == XmlReadMode.Fragment) { xdoc.AppendChild(xdoc.CreateElement("ds_sqlXmlWraPPeR")); @@ -6344,7 +6348,7 @@ namespace System.Data schema.LoadSchema(sSet, this); } - public void ReadXmlSchema(Stream stream) + public void ReadXmlSchema(Stream? stream) { if (stream == null) { @@ -6354,7 +6358,7 @@ namespace System.Data ReadXmlSchema(new XmlTextReader(stream), false); } - public void ReadXmlSchema(TextReader reader) + public void ReadXmlSchema(TextReader? reader) { if (reader == null) { @@ -6377,12 +6381,12 @@ namespace System.Data } } - public void ReadXmlSchema(XmlReader reader) + public void ReadXmlSchema(XmlReader? reader) { ReadXmlSchema(reader, false); } - internal void ReadXmlSchema(XmlReader reader, bool denyResolving) + internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, denyResolving={1}", ObjectID, denyResolving); try @@ -6399,7 +6403,7 @@ namespace System.Data return; } - DataTable currentTable = null; + DataTable? currentTable = null; if (!string.IsNullOrEmpty(_tableName)) { @@ -6456,10 +6460,7 @@ namespace System.Data if (Columns.Count == 0) { DataTable tempTable = currentTable; - if (tempTable != null) - { - tempTable.CloneTo(this, null, false); // we may have issue Amir - } + tempTable.CloneTo(this, null, false); // we may have issue Amir if (DataSet == null && _tableNamespace == null) { @@ -6499,22 +6500,24 @@ namespace System.Data dataset.Tables.Add(this); } + Debug.Assert(DataSet != null); + CloneHierarchy(currentTable, DataSet, null); foreach (DataTable tempTable in tableList) { - DataTable destinationTable = DataSet.Tables[tempTable._tableName, tempTable.Namespace]; - DataTable sourceTable = ds.Tables[tempTable._tableName, tempTable.Namespace]; + DataTable destinationTable = DataSet.Tables[tempTable._tableName, tempTable.Namespace]!; + DataTable sourceTable = ds.Tables[tempTable._tableName, tempTable.Namespace]!; foreach (Constraint tempConstrain in sourceTable.Constraints) { - ForeignKeyConstraint fkc = tempConstrain as ForeignKeyConstraint; // we have already cloned the UKC when cloning the datatable + ForeignKeyConstraint? fkc = tempConstrain as ForeignKeyConstraint; // we have already cloned the UKC when cloning the datatable if (fkc != null) { if (fkc.Table != fkc.RelatedTable) { - if (tableList.Contains(fkc.Table) && tableList.Contains(fkc.RelatedTable)) + if (tableList.Contains(fkc.Table!) && tableList.Contains(fkc.RelatedTable)) { - ForeignKeyConstraint newFKC = (ForeignKeyConstraint)fkc.Clone(destinationTable.DataSet); + ForeignKeyConstraint newFKC = (ForeignKeyConstraint)fkc.Clone(destinationTable.DataSet!)!; if (!destinationTable.Constraints.Contains(newFKC.ConstraintName)) { destinationTable.Constraints.Add(newFKC); // we know that the dest table is already in the table @@ -6542,10 +6545,10 @@ namespace System.Data hasExternaldependency = false; if (dc.Expression.Length != 0) { - DataColumn[] dependency = dc.DataExpression.GetDependency(); + DataColumn[] dependency = dc.DataExpression!.GetDependency(); for (int j = 0; j < dependency.Length; j++) { - if (!tableList.Contains(dependency[j].Table)) + if (!tableList.Contains(dependency[j].Table!)) { hasExternaldependency = true; break; @@ -6554,7 +6557,7 @@ namespace System.Data } if (!hasExternaldependency) { - DataSet.Tables[tempTable.TableName, tempTable.Namespace].Columns[dc.ColumnName].Expression = dc.Expression; + DataSet.Tables[tempTable.TableName, tempTable.Namespace]!.Columns[dc.ColumnName]!.Expression = dc.Expression; } } hasExternaldependency = false; @@ -6592,7 +6595,7 @@ namespace System.Data } } - public static XmlSchemaComplexType GetDataTableSchema(XmlSchemaSet schemaSet) + public static XmlSchemaComplexType GetDataTableSchema(XmlSchemaSet? schemaSet) { XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); @@ -6614,9 +6617,9 @@ namespace System.Data return type; } - XmlSchema IXmlSerializable.GetSchema() => GetSchema(); + XmlSchema? IXmlSerializable.GetSchema() => GetSchema(); - protected virtual XmlSchema GetSchema() + protected virtual XmlSchema? GetSchema() { if (GetType() == typeof(DataTable)) { @@ -6633,9 +6636,12 @@ namespace System.Data return XmlSchema.Read(new XmlTextReader(stream), null); } +// TODO: Enable after System.Private.Xml is annotated +#nullable disable +#pragma warning disable 8632 void IXmlSerializable.ReadXml(XmlReader reader) { - IXmlTextParser textReader = reader as IXmlTextParser; + IXmlTextParser? textReader = reader as IXmlTextParser; bool fNormalization = true; if (textReader != null) { @@ -6655,8 +6661,10 @@ namespace System.Data WriteXmlSchema(writer, false); WriteXml(writer, XmlWriteMode.DiffGram, false); } +#pragma warning restore 8632 +#nullable enable - protected virtual void ReadXmlSerializable(XmlReader reader) => ReadXml(reader, XmlReadMode.DiffGram, true); + protected virtual void ReadXmlSerializable(XmlReader? reader) => ReadXml(reader, XmlReadMode.DiffGram, true); // RowDiffIdUsageSection & DSRowDiffIdUsageSection Usage: // @@ -6686,7 +6694,7 @@ namespace System.Data // // do not allocate TLS data in RETAIL bits! [ThreadStatic] - internal static List t_usedTables; + internal static List? t_usedTables; #endif //DEBUG private DataTable _targetTable; @@ -6862,7 +6870,7 @@ namespace System.Data } } - internal void EvaluateExpressions(DataRow row, DataRowAction action, List cachedRows) + internal void EvaluateExpressions(DataRow row, DataRowAction action, List? cachedRows) { // evaluate all expressions for specified row if (action == DataRowAction.Add || @@ -6948,13 +6956,15 @@ namespace System.Data internal void EvaluateExpressions(DataColumn column) { - // evaluates all rows for expression from specified column + Debug.Assert(column._table != null); Debug.Assert(column.Computed, "Only computed columns should be re-evaluated."); + + // evaluates all rows for expression from specified column int count = column._table.Rows.Count; - if (column.DataExpression.IsTableAggregate() && count > 0) + if (column.DataExpression!.IsTableAggregate() && count > 0) { // this value is a constant across the table. - object aggCurrent = column.DataExpression.Evaluate(); + object aggCurrent = column.DataExpression!.Evaluate(); for (int j = 0; j < count; j++) { DataRow row = column._table.Rows[j]; @@ -6994,7 +7004,7 @@ namespace System.Data } } - column.Table.ResetInternalIndexes(column); + column._table.ResetInternalIndexes(column); EvaluateDependentExpressions(column); } @@ -7013,7 +7023,7 @@ namespace System.Data } } - internal void EvaluateDependentExpressions(List columns, DataRow row, DataRowVersion version, List cachedRows) + internal void EvaluateDependentExpressions(List? columns, DataRow row, DataRowVersion version, List? cachedRows) { if (columns == null) { @@ -7033,7 +7043,7 @@ namespace System.Data // if column expression references a local Table aggregate we need to recalc it for the each row in the local table DataRowVersion expressionVersion = (version == DataRowVersion.Proposed) ? DataRowVersion.Default : version; bool isConst = dc.DataExpression.IsTableAggregate(); //is expression constant for entire table? - object newValue = null; + object? newValue = null; if (isConst) { //if new value, just compute once @@ -7056,7 +7066,7 @@ namespace System.Data { newValue = dc.DataExpression.Evaluate(dr, expressionVersion); } - SilentlySetValue(dr, dc, expressionVersion, newValue); + SilentlySetValue(dr, dc, expressionVersion, newValue!); } } else @@ -7102,7 +7112,8 @@ namespace System.Data if (cachedRow != null && ((cachedRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || cachedRow._oldRecord != -1))) { // if deleted GetRecordFromVersion will throw - object newValue = dc.DataExpression.Evaluate(cachedRow, foreignVer); + // TODO: Possible bug, dc.DataExpression may be null + object newValue = dc.DataExpression!.Evaluate(cachedRow, foreignVer); SilentlySetValue(cachedRow, dc, foreignVer, newValue); } } @@ -7133,7 +7144,8 @@ namespace System.Data if (parentRow != null && ((parentRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || parentRow._oldRecord != -1))) { // if deleted GetRecordFromVersion will throw - object newValue = dc.DataExpression.Evaluate(parentRow, foreignVer); + // TODO: Possible bug, dc.DataExpression may be null + object newValue = dc.DataExpression!.Evaluate(parentRow, foreignVer); SilentlySetValue(parentRow, dc, foreignVer, newValue); } } @@ -7164,7 +7176,8 @@ namespace System.Data if (childRow != null && ((childRow.RowState != DataRowState.Deleted) && (version != DataRowVersion.Original || childRow._oldRecord != -1))) { // if deleted GetRecordFromVersion will throw - object newValue = dc.DataExpression.Evaluate(childRow, foreignVer); + // TODO: Possible bug, dc.DataExpression may be null + object newValue = dc.DataExpression!.Evaluate(childRow, foreignVer); SilentlySetValue(childRow, dc, foreignVer, newValue); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs index 59c7fc6..9597b35 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs @@ -6,6 +6,7 @@ using System.Collections; using System.ComponentModel; using System.Globalization; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -19,10 +20,10 @@ namespace System.Data private readonly DataSet _dataSet; private readonly ArrayList _list = new ArrayList(); private int _defaultNameIndex = 1; - private DataTable[] _delayedAddRangeTables; + private DataTable?[]? _delayedAddRangeTables; - private CollectionChangeEventHandler _onCollectionChangedDelegate; - private CollectionChangeEventHandler _onCollectionChangingDelegate; + private CollectionChangeEventHandler? _onCollectionChangedDelegate; + private CollectionChangeEventHandler? _onCollectionChangingDelegate; private static int s_objectTypeCount; // Bid counter private readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); @@ -33,7 +34,7 @@ namespace System.Data internal DataTableCollection(DataSet dataSet) { DataCommonEventSource.Log.Trace(" {0}, dataSet={1}", ObjectID, (dataSet != null) ? dataSet.ObjectID : 0); - _dataSet = dataSet; + _dataSet = dataSet!; } /// @@ -53,7 +54,7 @@ namespace System.Data try { // Perf: use the readonly _list field directly and let ArrayList check the range - return (DataTable)_list[index]; + return (DataTable)_list[index]!; } catch (ArgumentOutOfRangeException) { @@ -65,7 +66,7 @@ namespace System.Data /// /// Gets the table in the collection with the given name (not case-sensitive). /// - public DataTable this[string name] + public DataTable? this[string name] { get { @@ -78,11 +79,11 @@ namespace System.Data { throw ExceptionBuilder.NamespaceNameConflict(name); } - return (index < 0) ? null : (DataTable)_list[index]; + return (index < 0) ? null : (DataTable)_list[index]!; } } - public DataTable this[string name, string tableNamespace] + public DataTable? this[string name, string tableNamespace] { get { @@ -96,16 +97,16 @@ namespace System.Data { throw ExceptionBuilder.CaseInsensitiveNameConflict(name); } - return (index < 0) ? null : (DataTable)_list[index]; + return (index < 0) ? null : (DataTable)_list[index]!; } } // Case-sensitive search in Schema, data and diffgram loading - internal DataTable GetTable(string name, string ns) + internal DataTable? GetTable(string name, string ns) { for (int i = 0; i < _list.Count; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; if (table.TableName == name && table.Namespace == ns) { return table; @@ -116,13 +117,13 @@ namespace System.Data // Case-sensitive smart search: it will look for a table using the ns only if required to // resolve a conflict - internal DataTable GetTableSmart(string name, string ns) + internal DataTable? GetTableSmart(string name, string ns) { int fCount = 0; - DataTable fTable = null; + DataTable? fTable = null; for (int i = 0; i < _list.Count; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; if (table.TableName == name) { if (table.Namespace == ns) @@ -147,7 +148,7 @@ namespace System.Data try { OnCollectionChanging(new CollectionChangeEventArgs(CollectionChangeAction.Add, table)); - BaseAdd(table); + BaseAdd(table!); ArrayAdd(table); if (table.SetLocaleValue(_dataSet.Locale, false, false) || @@ -163,7 +164,7 @@ namespace System.Data } } - public void AddRange(DataTable[] tables) + public void AddRange(DataTable?[]? tables) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try @@ -176,7 +177,7 @@ namespace System.Data if (tables != null) { - foreach (DataTable table in tables) + foreach (DataTable? table in tables) { if (table != null) { @@ -194,14 +195,14 @@ namespace System.Data /// /// Creates a table with the given name and adds it to the collection. /// - public DataTable Add(string name) + public DataTable? Add(string? name) { DataTable table = new DataTable(name); Add(table); return table; } - public DataTable Add(string name, string tableNamespace) + public DataTable Add(string? name, string? tableNamespace) { DataTable table = new DataTable(name, tableNamespace); Add(table); @@ -221,7 +222,7 @@ namespace System.Data /// /// Occurs when the collection is changed. /// - public event CollectionChangeEventHandler CollectionChanged + public event CollectionChangeEventHandler? CollectionChanged { add { @@ -235,7 +236,7 @@ namespace System.Data } } - public event CollectionChangeEventHandler CollectionChanging + public event CollectionChangeEventHandler? CollectionChanging { add { @@ -256,7 +257,7 @@ namespace System.Data /// internal string AssignName() { - string newName = null; + string? newName = null; while (Contains(newName = MakeName(_defaultNameIndex))) { _defaultNameIndex++; @@ -271,7 +272,7 @@ namespace System.Data /// A DuplicateNameException is thrown if this collection already has a table with the same /// name (case insensitive). /// - private void BaseAdd(DataTable table) + private void BaseAdd([NotNull] DataTable table) { if (table == null) { @@ -358,7 +359,7 @@ namespace System.Data /// An ArgumentNullException is thrown if this table is null. An ArgumentException is thrown /// if this table doesn't belong to this collection or if this table is part of a relationship. /// - private void BaseRemove(DataTable table) + private void BaseRemove(DataTable? table) { if (CanRemove(table, true)) { @@ -366,15 +367,15 @@ namespace System.Data table.SetDataSet(null); } _list.Remove(table); - _dataSet.OnRemovedTable(table); + _dataSet.OnRemovedTable(table!); } /// /// Verifies if a given table can be removed from the collection. /// - public bool CanRemove(DataTable table) => CanRemove(table, false); + public bool CanRemove(DataTable? table) => CanRemove(table, false); - internal bool CanRemove(DataTable table, bool fThrowException) + internal bool CanRemove([NotNullWhen(true)] DataTable? table, bool fThrowException) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, table={1}, fThrowException={2}", ObjectID, (table != null) ? table.ObjectID : 0, fThrowException); try @@ -470,7 +471,7 @@ namespace System.Data _delayedAddRangeTables = null; } - BaseGroupSwitch(tables, oldLength, null, 0); + BaseGroupSwitch(tables, oldLength, Array.Empty(), 0); _list.Clear(); OnCollectionChanged(s_refreshEventArgs); @@ -484,7 +485,7 @@ namespace System.Data /// /// Checks if a table, specified by name, exists in the collection. /// - public bool Contains(string name) => (InternalIndexOf(name) >= 0); + public bool Contains(string? name) => (InternalIndexOf(name) >= 0); public bool Contains(string name, string tableNamespace) { @@ -501,7 +502,7 @@ namespace System.Data return (InternalIndexOf(name, tableNamespace) >= 0); } - internal bool Contains(string name, string tableNamespace, bool checkProperty, bool caseSensitive) + internal bool Contains(string name, string? tableNamespace, bool checkProperty, bool caseSensitive) { if (!caseSensitive) { @@ -512,9 +513,9 @@ namespace System.Data int count = _list.Count; for (int i = 0; i < count; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; // this may be needed to check whether the cascading is creating some conflicts - string ns = checkProperty ? table.Namespace : table._tableNamespace; + string? ns = checkProperty ? table.Namespace : table._tableNamespace; if (NamesEqual(table.TableName, name, true, _dataSet.Locale) == 1 && (ns == tableNamespace)) { return true; @@ -534,7 +535,7 @@ namespace System.Data int count = _list.Count; for (int i = 0; i < count; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; if (NamesEqual(table.TableName, name, true, _dataSet.Locale) == 1) { return true; @@ -559,19 +560,19 @@ namespace System.Data } for (int i = 0; i < _list.Count; ++i) { - array[index + i] = (DataTable)_list[i]; + array[index + i] = (DataTable)_list[i]!; } } /// /// Returns the index of a specified . /// - public int IndexOf(DataTable table) + public int IndexOf(DataTable? table) { int tableCount = _list.Count; for (int i = 0; i < tableCount; ++i) { - if (table == (DataTable)_list[i]) + if (table == (DataTable)_list[i]!) { return i; } @@ -584,7 +585,7 @@ namespace System.Data /// table with the given name (case insensitive), or -1 if the table /// doesn't exist in the collection. /// - public int IndexOf(string tableName) + public int IndexOf(string? tableName) { int index = InternalIndexOf(tableName); return (index < 0) ? -1 : index; @@ -622,7 +623,7 @@ namespace System.Data // -1: No match // -2: At least two matches with different cases // -3: At least two matches with different namespaces - internal int InternalIndexOf(string tableName) + internal int InternalIndexOf(string? tableName) { int cachedI = -1; if ((null != tableName) && (0 < tableName.Length)) @@ -631,7 +632,7 @@ namespace System.Data int result = 0; for (int i = 0; i < count; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; result = NamesEqual(table.TableName, tableName, false, _dataSet.Locale); if (result == 1) { @@ -640,7 +641,7 @@ namespace System.Data // if any let's return (-3) otherwise... for (int j = i + 1; j < count; j++) { - DataTable dupTable = (DataTable)_list[j]; + DataTable dupTable = (DataTable)_list[j]!; if (NamesEqual(dupTable.TableName, tableName, false, _dataSet.Locale) == 1) return -3; } @@ -668,7 +669,7 @@ namespace System.Data int result = 0; for (int i = 0; i < count; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; result = NamesEqual(table.TableName, tableName, false, _dataSet.Locale); if ((result == 1) && (table.Namespace == tableNamespace)) return i; @@ -684,7 +685,7 @@ namespace System.Data { if (_delayedAddRangeTables != null) { - foreach (DataTable table in _delayedAddRangeTables) + foreach (DataTable? table in _delayedAddRangeTables) { if (table != null) { @@ -737,10 +738,10 @@ namespace System.Data int tableCount = _list.Count; for (int i = 0; i < tableCount; i++) { - DataTable table = (DataTable)_list[i]; + DataTable table = (DataTable)_list[i]!; if (NamesEqual(name, table.TableName, true, locale) != 0 && (tbNamespace == table.Namespace)) { - throw ExceptionBuilder.DuplicateTableName(((DataTable)_list[i]).TableName); + throw ExceptionBuilder.DuplicateTableName(((DataTable)_list[i]!).TableName); } } if (NamesEqual(name, MakeName(_defaultNameIndex), true, locale) != 0) @@ -796,7 +797,7 @@ namespace System.Data long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}, name='{1}'", ObjectID, name); try { - DataTable dt = this[name]; + DataTable? dt = this[name]; if (dt == null) { throw ExceptionBuilder.TableNotInTheDataSet(name); @@ -819,7 +820,7 @@ namespace System.Data { throw ExceptionBuilder.ArgumentNull(nameof(tableNamespace)); } - DataTable dt = this[name, tableNamespace]; + DataTable? dt = this[name, tableNamespace]; if (dt == null) { throw ExceptionBuilder.TableNotInTheDataSet(name); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs index 1b210d5..c5a04f7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableExtensions.cs @@ -72,7 +72,7 @@ namespace System.Data /// if source is null /// if table is null /// if source DataRow is in Deleted or Detached state - public static void CopyToDataTable(this IEnumerable source, DataTable table, LoadOption options, FillErrorEventHandler errorHandler) + public static void CopyToDataTable(this IEnumerable source, DataTable table, LoadOption options, FillErrorEventHandler? errorHandler) where T : DataRow { DataSetUtil.CheckArgumentNull(source, nameof(source)); @@ -80,7 +80,7 @@ namespace System.Data LoadTableFromEnumerable(source, table, options, errorHandler); } - private static DataTable LoadTableFromEnumerable(IEnumerable source, DataTable table, LoadOption? options, FillErrorEventHandler errorHandler) + private static DataTable LoadTableFromEnumerable(IEnumerable source, DataTable? table, LoadOption? options, FillErrorEventHandler? errorHandler) where T : DataRow { if (options.HasValue) @@ -141,7 +141,7 @@ namespace System.Data continue; } - object[] values = null; + object?[]? values = null; try { // 'recoverable' error block @@ -179,7 +179,7 @@ namespace System.Data throw; } - FillErrorEventArgs fillError = null; + FillErrorEventArgs? fillError = null; if (null != errorHandler) { fillError = new FillErrorEventArgs(table, values) @@ -202,7 +202,9 @@ namespace System.Data else { // user may have changed exception to throw in handler - throw fillError.Errors; + // FillErrorEventArgs instances constructed in the codebase always have + // their Errors property set to not-null immediately afterwards + throw fillError.Errors!; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs index 26eb178..59b2a5c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableReader.cs @@ -10,12 +10,12 @@ namespace System.Data { private readonly DataTable[] _tables; private bool _isOpen = true; - private DataTable _schemaTable; + private DataTable? _schemaTable; private int _tableCounter = -1; private int _rowCounter = -1; - private DataTable _currentDataTable; - private DataRow _currentDataRow; + private DataTable _currentDataTable = default!; // Always initialized in Init + private DataRow? _currentDataRow; private bool _hasRows = true; private bool _reachEORows; @@ -23,7 +23,7 @@ namespace System.Data private bool _schemaIsChanged; private bool _started; private bool _readerIsInvalid; - private DataTableReaderListener _listener; + private DataTableReaderListener _listener = default!; // Always initialized in Init private bool _tableCleared; public DataTableReader(DataTable dataTable) @@ -125,7 +125,7 @@ namespace System.Data _listener.CleanUp(); } - _listener = null; + _listener = null!; _schemaTable = null; _isOpen = false; } @@ -335,7 +335,7 @@ namespace System.Data ValidateReader(); try { - return (bool)_currentDataRow[ordinal]; + return (bool)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -351,7 +351,7 @@ namespace System.Data ValidateReader(); try { - return (byte)_currentDataRow[ordinal]; + return (byte)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -361,14 +361,14 @@ namespace System.Data } } - public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length) + public override long GetBytes(int ordinal, long dataIndex, byte[]? buffer, int bufferIndex, int length) { ValidateState(nameof(GetBytes)); ValidateReader(); byte[] tempBuffer; try { - tempBuffer = (byte[])_currentDataRow[ordinal]; + tempBuffer = (byte[])_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -414,7 +414,7 @@ namespace System.Data ValidateReader(); try { - return (char)_currentDataRow[ordinal]; + return (char)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -424,14 +424,14 @@ namespace System.Data } } - public override long GetChars(int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length) + public override long GetChars(int ordinal, long dataIndex, char[]? buffer, int bufferIndex, int length) { ValidateState(nameof(GetChars)); ValidateReader(); char[] tempBuffer; try { - tempBuffer = (char[])_currentDataRow[ordinal]; + tempBuffer = (char[])_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -484,7 +484,7 @@ namespace System.Data ValidateReader(); try { - return (DateTime)_currentDataRow[ordinal]; + return (DateTime)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -500,7 +500,7 @@ namespace System.Data ValidateReader(); try { - return (decimal)_currentDataRow[ordinal]; + return (decimal)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -516,7 +516,7 @@ namespace System.Data ValidateReader(); try { - return (double)_currentDataRow[ordinal]; + return (double)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection @@ -546,7 +546,7 @@ namespace System.Data ValidateReader(); try { - return (float)_currentDataRow[ordinal]; + return (float)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -562,7 +562,7 @@ namespace System.Data ValidateReader(); try { - return (Guid)_currentDataRow[ordinal]; + return (Guid)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -578,7 +578,7 @@ namespace System.Data ValidateReader(); try { - return (short)_currentDataRow[ordinal]; + return (short)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -594,7 +594,7 @@ namespace System.Data ValidateReader(); try { - return (int)_currentDataRow[ordinal]; + return (int)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -610,7 +610,7 @@ namespace System.Data ValidateReader(); try { - return (long)_currentDataRow[ordinal]; + return (long)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -640,7 +640,7 @@ namespace System.Data { ValidateOpen(nameof(GetOrdinal)); ValidateReader(); - DataColumn dc = _currentDataTable.Columns[name]; + DataColumn? dc = _currentDataTable.Columns[name]; if (dc != null) { @@ -658,7 +658,7 @@ namespace System.Data ValidateReader(); try { - return (string)_currentDataRow[ordinal]; + return (string)_currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -674,7 +674,7 @@ namespace System.Data ValidateReader(); try { - return _currentDataRow[ordinal]; + return _currentDataRow![ordinal]; } catch (IndexOutOfRangeException e) { @@ -694,7 +694,7 @@ namespace System.Data throw ExceptionBuilder.ArgumentNull(nameof(values)); } - Array.Copy(_currentDataRow.ItemArray, values, _currentDataRow.ItemArray.Length > values.Length ? values.Length : _currentDataRow.ItemArray.Length); + Array.Copy(_currentDataRow!.ItemArray, values, _currentDataRow.ItemArray.Length > values.Length ? values.Length : _currentDataRow.ItemArray.Length); return (_currentDataRow.ItemArray.Length > values.Length ? values.Length : _currentDataRow.ItemArray.Length); } public override bool IsDBNull(int ordinal) @@ -703,7 +703,7 @@ namespace System.Data ValidateReader(); try { - return (_currentDataRow.IsNull(ordinal)); + return (_currentDataRow!.IsNull(ordinal)); } catch (IndexOutOfRangeException e) { @@ -832,7 +832,7 @@ namespace System.Data if (dc.Expression.Length != 0) { bool hasExternalDependency = false; - DataColumn[] dependency = dc.DataExpression.GetDependency(); + DataColumn[] dependency = dc.DataExpression!.GetDependency(); for (int j = 0; j < dependency.Length; j++) { if (dependency[j].Table != table) @@ -897,7 +897,8 @@ namespace System.Data if ((_currentDataRow == null) || (_currentDataTable == null)) { ReaderIsInvalid = true; - throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); + // TODO: This will throw an NRE + throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable!.TableName); } //See if without any event raing, if our rows are deleted, or removed! Reader is not invalid, user should be able to read and reach goo row diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs index ac8532e..8d74e386 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableReaderListener.cs @@ -86,7 +86,7 @@ namespace System.Data private void DataTableCleared(object sender, DataTableClearEventArgs e) { - DataTableReader reader = (DataTableReader)_readerWeak.Target; + DataTableReader? reader = (DataTableReader?)_readerWeak.Target; if (reader != null) { reader.DataTableCleared(); @@ -99,7 +99,7 @@ namespace System.Data private void SchemaChanged(object sender, CollectionChangeEventArgs e) { - DataTableReader reader = (DataTableReader)_readerWeak.Target; + DataTableReader? reader = (DataTableReader?)_readerWeak.Target; if (reader != null) { reader.SchemaChanged(); @@ -112,7 +112,7 @@ namespace System.Data private void DataChanged(object sender, DataRowChangeEventArgs args) { - DataTableReader reader = (DataTableReader)_readerWeak.Target; + DataTableReader? reader = (DataTableReader?)_readerWeak.Target; if (reader != null) { reader.DataChanged(args); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataView.cs b/src/libraries/System.Data.Common/src/System/Data/DataView.cs index 645a5a2..931f1eb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataView.cs @@ -19,22 +19,22 @@ namespace System.Data [DefaultEvent("PositionChanged")] public class DataView : MarshalByValueComponent, IBindingListView, System.ComponentModel.ITypedList, ISupportInitializeNotification { - private DataViewManager _dataViewManager; - private DataTable _table; + private DataViewManager? _dataViewManager; + private DataTable? _table; private bool _locked; - private Index _index; - private Dictionary _findIndexes; + private Index? _index; + private Dictionary? _findIndexes; private string _sort = string.Empty; /// Allow a user implemented comparison of two DataRow /// User must use correct DataRowVersion in comparison or index corruption will happen - private System.Comparison _comparison; + private System.Comparison? _comparison; /// /// IFilter will allow LinqDataView to wrap instead of using a DataExpression /// - private IFilter _rowFilter; + private IFilter? _rowFilter; private DataViewRowState _recordStates = DataViewRowState.CurrentRows; @@ -45,15 +45,15 @@ namespace System.Data private bool _allowDelete = true; private bool _applyDefaultSort; - internal DataRow _addNewRow; - private ListChangedEventArgs _addNewMoved; + internal DataRow? _addNewRow; + private ListChangedEventArgs? _addNewMoved; - private System.ComponentModel.ListChangedEventHandler _onListChanged; + private System.ComponentModel.ListChangedEventHandler? _onListChanged; internal static ListChangedEventArgs s_resetEventArgs = new ListChangedEventArgs(ListChangedType.Reset, -1); - private DataTable _delayedTable; - private string _delayedRowFilter; - private string _delayedSort; + private DataTable? _delayedTable; + private string? _delayedRowFilter; + private string? _delayedSort; private DataViewRowState _delayedRecordStates = (DataViewRowState)(-1); private bool _fInitInProgress; private bool _fEndInitInProgress; @@ -80,7 +80,7 @@ namespace System.Data private DataRowReferenceComparer() { } - public bool Equals(DataRow x, DataRow y) => x == (object)y; + public bool Equals(DataRow? x, DataRow? y) => x == (object?)y; public int GetHashCode(DataRow obj) => obj._objectID; } @@ -90,7 +90,7 @@ namespace System.Data private static int s_objectTypeCount; // Bid counter private readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); - internal DataView(DataTable table, bool locked) + internal DataView(DataTable? table, bool locked) { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" {0}, table={1}, locked={2}", ObjectID, (table != null) ? table.ObjectID : 0, locked); @@ -113,7 +113,7 @@ namespace System.Data /// Initializes a new instance of the class with the /// specified . /// - public DataView(DataTable table) : this(table, false) + public DataView(DataTable? table) : this(table, false) { SetIndex2("", DataViewRowState.CurrentRows, null, true); } @@ -122,7 +122,7 @@ namespace System.Data /// Initializes a new instance of the class with the /// specified . /// - public DataView(DataTable table, string RowFilter, string Sort, DataViewRowState RowState) + public DataView(DataTable table, string? RowFilter, string? Sort, DataViewRowState RowState) { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" {0}, table={1}, RowFilter='{2}', Sort='{3}', RowState={4}", @@ -162,7 +162,7 @@ namespace System.Data SetIndex(Sort, RowState, newFilter); } - internal DataView(DataTable table, System.Predicate predicate, System.Comparison comparison, DataViewRowState RowState) + internal DataView(DataTable table, System.Predicate? predicate, System.Comparison? comparison, DataViewRowState RowState) { GC.SuppressFinalize(this); DataCommonEventSource.Log.Trace(" %d#, table=%d, RowState=%d{ds.DataViewRowState}\n", @@ -285,7 +285,7 @@ namespace System.Data /// Gets the associated with this . /// [Browsable(false)] - public DataViewManager DataViewManager => _dataViewManager; + public DataViewManager? DataViewManager => _dataViewManager; [Browsable(false)] public bool IsInitialized => !_fInitInProgress; @@ -303,11 +303,11 @@ namespace System.Data /// Gets or sets the expression used to filter which rows are viewed in the . /// [DefaultValue("")] - public virtual string RowFilter + public virtual string? RowFilter { get { - DataExpression expression = (_rowFilter as DataExpression); + DataExpression? expression = (_rowFilter as DataExpression); return (expression == null ? "" : expression.Expression); // CONSIDER: return optimized expression here } set @@ -338,11 +338,11 @@ namespace System.Data /// The predicate delegate that will determine if a DataRow should be contained within the view. /// This RowPredicate property is mutually exclusive with the RowFilter property. /// - internal Predicate RowPredicate + internal Predicate? RowPredicate { get { - RowPredicateFilter filter = (GetFilter() as RowPredicateFilter); + RowPredicateFilter? filter = (GetFilter() as RowPredicateFilter); return ((null != filter) ? filter._predicateFilter : null); } set @@ -451,7 +451,7 @@ namespace System.Data /// Allow a user implemented comparison of two DataRow /// User must use correct DataRowVersion in comparison or index corruption will happen - internal System.Comparison SortComparison + internal System.Comparison? SortComparison { get { return _comparison; } set @@ -473,7 +473,7 @@ namespace System.Data [TypeConverterAttribute(typeof(DataTableTypeConverter))] [DefaultValue(null)] [RefreshProperties(RefreshProperties.All)] - public DataTable Table + public DataTable? Table { get { return _table; } set @@ -518,7 +518,7 @@ namespace System.Data } } - object IList.this[int recordIndex] + object? IList.this[int recordIndex] { get { return this[recordIndex]; } set { throw ExceptionBuilder.SetIListObject(); } @@ -554,7 +554,8 @@ namespace System.Data Debug.Assert(null == _addNewRow, "AddNew addNewRow is not null"); - _addNewRow = _table.NewRow(); + // TODO: This will throw NRE if _table isn't set (e.g. default ctor) + _addNewRow = _table!.NewRow(); DataRowView drv = new DataRowView(this, _addNewRow); _rowViewCache.Add(_addNewRow, drv); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, IndexOf(drv))); @@ -721,33 +722,36 @@ namespace System.Data public int Find(object key) => FindByKey(key); /// Find index of a DataRowView instance that matches the specified primary key value. - internal virtual int FindByKey(object key) => _index.FindRecordByKey(key); + // TODO: This will throw NRE if _index isn't set (e.g. default ctor) + internal virtual int FindByKey(object key) => _index!.FindRecordByKey(key); /// /// Finds a row in the by the specified primary key values. /// - public int Find(object[] key) => FindByKey(key); + public int Find(object?[] key) => FindByKey(key); /// Find index of a DataRowView instance that matches the specified primary key values. - internal virtual int FindByKey(object[] key) => _index.FindRecordByKey(key); + // TODO: This will throw NRE if _index isn't set (e.g. default ctor) + internal virtual int FindByKey(object?[] key) => _index!.FindRecordByKey(key); /// /// Finds a row in the by the specified primary key value. /// - public DataRowView[] FindRows(object key) => FindRowsByKey(new object[] { key }); + public DataRowView[] FindRows(object? key) => FindRowsByKey(new object?[] { key }); /// /// Finds a row in the by the specified primary key values. /// - public DataRowView[] FindRows(object[] key) => FindRowsByKey(key); + public DataRowView[] FindRows(object?[] key) => FindRowsByKey(key); /// Find DataRowView instances that match the specified primary key values. - internal virtual DataRowView[] FindRowsByKey(object[] key) + internal virtual DataRowView[] FindRowsByKey(object?[] key) { long logScopeId = DataCommonEventSource.Log.EnterScope(" {0}", ObjectID); try { - Range range = _index.FindRecords(key); + // TODO: This will throw NRE if _index isn't set (e.g. default ctor) + Range range = _index!.FindRecords(key); return GetDataRowViewFromRange(range); } finally @@ -759,7 +763,8 @@ namespace System.Data /// This method exists for LinqDataView to keep a level of abstraction away from the RBTree internal Range FindRecords(Index.ComparisonBySelector comparison, TKey key) where TRow : DataRow { - return _index.FindRecords(comparison, key); + // TODO: This will throw NRE if _index isn't set (e.g. default ctor) + return _index!.FindRecords(comparison, key); } /// Convert a Range into a DataRowView[]. @@ -791,7 +796,7 @@ namespace System.Data // MaintainDataView will translate the ItemAdded from the RowCollection into // into either an ItemMoved or no event, since it didn't change position. // also possible it's added to the RowCollection but filtered out of the view. - _table.Rows.Add(newRow); + _table!.Rows.Add(newRow); } else { @@ -834,7 +839,7 @@ namespace System.Data bool IList.IsFixedSize => false; - int IList.Add(object value) + int IList.Add(object? value) { if (value == null) { @@ -850,13 +855,13 @@ namespace System.Data throw ExceptionBuilder.CanNotClear(); } - bool IList.Contains(object value) => (0 <= IndexOf(value as DataRowView)); + bool IList.Contains(object? value) => (0 <= IndexOf(value as DataRowView)); - int IList.IndexOf(object value) => IndexOf(value as DataRowView); + int IList.IndexOf(object? value) => IndexOf(value as DataRowView); /// Return positional index of a in this DataView /// Behavioral change: will now return -1 once a DataRowView becomes detached. - internal int IndexOf(DataRowView rowview) + internal int IndexOf(DataRowView? rowview) { if (null != rowview) { @@ -866,7 +871,7 @@ namespace System.Data } if ((null != _index) && (DataRowState.Detached != rowview.Row.RowState)) { - DataRowView cached; // verify the DataRowView is one we currently track - not something previously detached + DataRowView? cached; // verify the DataRowView is one we currently track - not something previously detached if (_rowViewCache.TryGetValue(rowview.Row, out cached) && cached == (object)rowview) { return IndexOfDataRowView(rowview); @@ -881,15 +886,15 @@ namespace System.Data // rowview.GetRecord() may return the proposed record // the index will only contain the original or current record, never proposed. // return index.GetIndex(rowview.GetRecord()); - return _index.GetIndex(rowview.Row.GetRecordFromVersion(rowview.Row.GetDefaultRowVersion(RowStateFilter) & ~DataRowVersion.Proposed)); + return _index!.GetIndex(rowview.Row.GetRecordFromVersion(rowview.Row.GetDefaultRowVersion(RowStateFilter) & ~DataRowVersion.Proposed)); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { throw ExceptionBuilder.InsertExternalObject(); } - void IList.Remove(object value) + void IList.Remove(object? value) { int index = IndexOf(value as DataRowView); if (0 <= index) @@ -905,14 +910,14 @@ namespace System.Data void IList.RemoveAt(int index) => Delete(index); - internal Index GetFindIndex(string column, bool keepIndex) + internal Index? GetFindIndex(string column, bool keepIndex) { if (_findIndexes == null) { _findIndexes = new Dictionary(); } - Index findIndex; + Index? findIndex; if (_findIndexes.TryGetValue(column, out findIndex)) { if (!keepIndex) @@ -929,7 +934,7 @@ namespace System.Data { if (keepIndex) { - findIndex = _table.GetIndex(column, _recordStates, GetFilter()); + findIndex = _table!.GetIndex(column, _recordStates, GetFilter()); _findIndexes[column] = findIndex; findIndex.AddRef(); } @@ -940,7 +945,8 @@ namespace System.Data #endregion #region IBindingList implementation - +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable bool IBindingList.AllowNew => AllowNew; object IBindingList.AddNew() => AddNew(); bool IBindingList.AllowEdit => AllowEdit; @@ -961,9 +967,10 @@ namespace System.Data return null; } - ListSortDirection IBindingList.SortDirection => (_index._indexFields.Length == 1 && _index._indexFields[0].IsDescending) ? + ListSortDirection IBindingList.SortDirection => (_index!._indexFields.Length == 1 && _index._indexFields[0].IsDescending) ? ListSortDirection.Descending : ListSortDirection.Ascending; +#nullable enable #endregion #region ListChanged & Initialized events @@ -971,7 +978,7 @@ namespace System.Data /// /// Occurs when the list managed by the changes. /// - public event ListChangedEventHandler ListChanged + public event ListChangedEventHandler? ListChanged { add { @@ -985,7 +992,7 @@ namespace System.Data } } - public event EventHandler Initialized; + public event EventHandler? Initialized; #endregion @@ -1004,13 +1011,13 @@ namespace System.Data if (property != null) { bool created = false; - Index findIndex = null; + Index? findIndex = null; try { if ((null == _findIndexes) || !_findIndexes.TryGetValue(property.Name, out findIndex)) { created = true; - findIndex = _table.GetIndex(property.Name, _recordStates, GetFilter()); + findIndex = _table!.GetIndex(property.Name, _recordStates, GetFilter()); findIndex.AddRef(); } Range recordRange = findIndex.FindRecords(key); @@ -1018,7 +1025,7 @@ namespace System.Data if (!recordRange.IsNull) { // check to see if key is equal - return _index.GetIndex(findIndex.GetRecord(recordRange.Min)); + return _index!.GetIndex(findIndex.GetRecord(recordRange.Min)); } } finally @@ -1075,7 +1082,7 @@ namespace System.Data throw ExceptionBuilder.ArgumentNull(nameof(PropertyDescriptor)); } - if (!_table.Columns.Contains(property.Name)) + if (!_table!.Columns.Contains(property.Name)) { // just check if column does not exist, we will handle duplicate column in Sort throw ExceptionBuilder.ColumnToSortIsOutOfRange(property.Name); @@ -1111,6 +1118,8 @@ namespace System.Data return resultString.ToString(); } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable void IBindingListView.RemoveFilter() { DataCommonEventSource.Log.Trace(" {0}", ObjectID); @@ -1122,6 +1131,7 @@ namespace System.Data get { return RowFilter; } set { RowFilter = value; } } +#nullable enable ListSortDescriptionCollection IBindingListView.SortDescriptions => GetSortDescriptions(); @@ -1166,10 +1176,10 @@ namespace System.Data } else { - DataSet dataSet = _table.DataSet; + DataSet? dataSet = _table.DataSet; if (dataSet != null) { - DataTable foundTable = dataSet.FindTable(_table, listAccessors, 0); + DataTable? foundTable = dataSet.FindTable(_table, listAccessors, 0); if (foundTable != null) { return foundTable.TableName; @@ -1190,13 +1200,13 @@ namespace System.Data } else { - DataSet dataSet = _table.DataSet; + DataSet? dataSet = _table.DataSet; if (dataSet == null) { return new PropertyDescriptorCollection(null); } - DataTable foundTable = dataSet.FindTable(_table, listAccessors, 0); + DataTable? foundTable = dataSet.FindTable(_table, listAccessors, 0); if (foundTable != null) { return foundTable.GetPropertyDescriptorCollection(null); @@ -1211,7 +1221,7 @@ namespace System.Data /// /// Gets the filter for the . /// - internal virtual IFilter GetFilter() => _rowFilter; + internal virtual IFilter? GetFilter() => _rowFilter; private int GetRecord(int recordIndex) { @@ -1220,8 +1230,8 @@ namespace System.Data throw ExceptionBuilder.RowOutOfRange(recordIndex); } - return recordIndex == _index.RecordCount ? - _addNewRow.GetDefaultRecord() : + return recordIndex == _index!.RecordCount ? + _addNewRow!.GetDefaultRecord() : _index.GetRecord(recordIndex); } @@ -1239,10 +1249,10 @@ namespace System.Data // then this special case code would go away return _addNewRow; } - return _table._recordManager[GetRecord(index)]; + return _table!._recordManager[GetRecord(index)]!; } - private DataRowView GetRowView(int record) => GetRowView(_table._recordManager[record]); + private DataRowView GetRowView(int record) => GetRowView(_table!._recordManager[record]!); private DataRowView GetRowView(DataRow dr) => _rowViewCache[dr]; @@ -1253,7 +1263,7 @@ namespace System.Data OnListChanged(e); } - if (_addNewRow != null && _index.RecordCount == 0) + if (_addNewRow != null && _index!.RecordCount == 0) { FinishAddNew(false); } @@ -1287,9 +1297,9 @@ namespace System.Data IndexListChanged(this, e); } - internal void MaintainDataView(ListChangedType changedType, DataRow row, bool trackAddRemove) + internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool trackAddRemove) { - DataRowView buffer = null; + DataRowView? buffer = null; switch (changedType) { case ListChangedType.ItemAdded: @@ -1366,8 +1376,8 @@ namespace System.Data DataCommonEventSource.Log.Trace(" {0}, ListChangedType={1}", ObjectID, e.ListChangedType); try { - DataColumn col = null; - string propertyName = null; + DataColumn? col = null; + string? propertyName = null; switch (e.ListChangedType) { case ListChangedType.ItemChanged: @@ -1447,14 +1457,14 @@ namespace System.Data { if (IsOpen) { - _index.Reset(); + _index!.Reset(); } } internal void ResetRowViewCache() { Dictionary rvc = new Dictionary(CountFromIndex, DataRowReferenceComparer.s_default); - DataRowView drv; + DataRowView? drv; if (null != _index) { @@ -1462,7 +1472,7 @@ namespace System.Data RBTree.RBTreeEnumerator iterator = _index.GetEnumerator(0); while (iterator.MoveNext()) { - DataRow row = _table._recordManager[iterator.Current]; + DataRow row = _table!._recordManager[iterator.Current]!; if (!_rowViewCache.TryGetValue(row, out drv)) { drv = new DataRowView(this, row); @@ -1480,7 +1490,7 @@ namespace System.Data _rowViewCache = rvc; } - internal void SetDataViewManager(DataViewManager dataViewManager) + internal void SetDataViewManager(DataViewManager? dataViewManager) { if (_table == null) throw ExceptionBuilder.CanNotUse(); @@ -1517,12 +1527,12 @@ namespace System.Data } } - internal virtual void SetIndex(string newSort, DataViewRowState newRowStates, IFilter newRowFilter) + internal virtual void SetIndex(string newSort, DataViewRowState newRowStates, IFilter? newRowFilter) { SetIndex2(newSort, newRowStates, newRowFilter, true); } - internal void SetIndex2(string newSort, DataViewRowState newRowStates, IFilter newRowFilter, bool fireEvent) + internal void SetIndex2(string newSort, DataViewRowState newRowStates, IFilter? newRowFilter, bool fireEvent) { DataCommonEventSource.Log.Trace(" {0}, newSort='{1}', newRowStates={2}", ObjectID, newSort, newRowStates); _sort = newSort; @@ -1574,7 +1584,7 @@ namespace System.Data if (_open != _shouldOpen || force) { _open = _shouldOpen; - Index newIndex = null; + Index? newIndex = null; if (_open) { if (_table != null) @@ -1628,34 +1638,34 @@ namespace System.Data internal void ChildRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataRelationPropertyDescriptor NullProp = null; + DataRelationPropertyDescriptor? NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : - /*default*/ null + /*default*/ null! // TODO: This will cause an NRE ); } internal void ParentRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataRelationPropertyDescriptor NullProp = null; + DataRelationPropertyDescriptor? NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : - /*default*/ null + /*default*/ null! // TODO: This will cause an NRE ); } protected virtual void ColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataColumnPropertyDescriptor NullProp = null; + DataColumnPropertyDescriptor? NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataColumnPropertyDescriptor((System.Data.DataColumn)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataColumnPropertyDescriptor((System.Data.DataColumn)e.Element)) : - /*default*/ null + /*default*/ null! // TODO: This will cause an NRE ); } @@ -1665,13 +1675,13 @@ namespace System.Data public DataTable ToTable() => ToTable(null, false, Array.Empty()); - public DataTable ToTable(string tableName) => + public DataTable ToTable(string? tableName) => ToTable(tableName, false, Array.Empty()); public DataTable ToTable(bool distinct, params string[] columnNames) => ToTable(null, distinct, columnNames); - public DataTable ToTable(string tableName, bool distinct, params string[] columnNames) + public DataTable ToTable(string? tableName, bool distinct, params string[] columnNames) { DataCommonEventSource.Log.Trace(" {0}, TableName='{1}', distinct={2}", ObjectID, tableName, distinct); @@ -1681,7 +1691,7 @@ namespace System.Data } DataTable dt = new DataTable(); - dt.Locale = _table.Locale; + dt.Locale = _table!.Locale; dt.CaseSensitive = _table.CaseSensitive; dt.TableName = ((null != tableName) ? tableName : _table.TableName); dt.Namespace = _table.Namespace; @@ -1689,7 +1699,7 @@ namespace System.Data if (columnNames.Length == 0) { - columnNames = new string[Table.Columns.Count]; + columnNames = new string[Table!.Columns.Count]; for (int i = 0; i < columnNames.Length; i++) { columnNames[i] = Table.Columns[i].ColumnName; @@ -1702,7 +1712,7 @@ namespace System.Data for (int i = 0; i < columnNames.Length; i++) { - DataColumn dc = Table.Columns[columnNames[i]]; + DataColumn? dc = Table!.Columns[columnNames[i]]; if (dc == null) { throw ExceptionBuilder.ColumnNotInTheUnderlyingTable(columnNames[i], Table.TableName); @@ -1751,7 +1761,7 @@ namespace System.Data /// If is equivalent to the current view with regards to all properties. /// and may differ by . /// - public virtual bool Equals(DataView view) + public virtual bool Equals(DataView? view) { if ((null == view) || Table != view.Table || diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs index 0eec69c..b278f16 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewListener.cs @@ -10,8 +10,8 @@ namespace System.Data internal sealed class DataViewListener { private readonly WeakReference _dvWeak; - private DataTable _table; - private Index _index; + private DataTable? _table; + private Index? _index; /// internal readonly int _objectID; @@ -24,7 +24,7 @@ namespace System.Data private void ChildRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataView dv = (DataView)_dvWeak.Target; + DataView? dv = (DataView?)_dvWeak.Target; if (dv != null) { dv.ChildRelationCollectionChanged(sender, e); @@ -37,7 +37,7 @@ namespace System.Data private void ParentRelationCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataView dv = (DataView)_dvWeak.Target; + DataView? dv = (DataView?)_dvWeak.Target; if (dv != null) { dv.ParentRelationCollectionChanged(sender, e); @@ -50,7 +50,7 @@ namespace System.Data private void ColumnCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataView dv = (DataView)_dvWeak.Target; + DataView? dv = (DataView?)_dvWeak.Target; if (dv != null) { dv.ColumnCollectionChangedInternal(sender, e); @@ -64,9 +64,9 @@ namespace System.Data /// /// Maintain the DataView before is raised. /// - internal void MaintainDataView(ListChangedType changedType, DataRow row, bool trackAddRemove) + internal void MaintainDataView(ListChangedType changedType, DataRow? row, bool trackAddRemove) { - DataView dv = (DataView)_dvWeak.Target; + DataView? dv = (DataView?)_dvWeak.Target; if (dv != null) { dv.MaintainDataView(changedType, row, trackAddRemove); @@ -79,7 +79,7 @@ namespace System.Data internal void IndexListChanged(ListChangedEventArgs e) { - DataView dv = (DataView)_dvWeak.Target; + DataView? dv = (DataView?)_dvWeak.Target; if (dv != null) { dv.IndexListChangedInternal(e); @@ -90,7 +90,7 @@ namespace System.Data } } - internal void RegisterMetaDataEvents(DataTable table) + internal void RegisterMetaDataEvents(DataTable? table) { Debug.Assert(null == _table, "DataViewListener already registered table"); _table = table; @@ -118,7 +118,7 @@ namespace System.Data private void UnregisterMetaDataEvents(bool updateListeners) { - DataTable table = _table; + DataTable? table = _table; _table = null; if (table != null) @@ -162,7 +162,7 @@ namespace System.Data internal void UnregisterListChangedEvent() { - Index index = _index; + Index? index = _index; _index = null; if (index != null) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs index 1c5ea20..e10db24 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Xml; @@ -12,7 +13,7 @@ namespace System.Data public class DataViewManager : MarshalByValueComponent, IBindingList, System.ComponentModel.ITypedList { private DataViewSettingCollection _dataViewSettingsCollection; - private DataSet _dataSet; + private DataSet? _dataSet; private readonly DataViewManagerListItemTypeDescriptor _item; private readonly bool _locked; internal int _nViews; @@ -21,9 +22,9 @@ namespace System.Data public DataViewManager() : this(null, false) { } - public DataViewManager(DataSet dataSet) : this(dataSet, false) { } + public DataViewManager(DataSet? dataSet) : this(dataSet, false) { } - internal DataViewManager(DataSet dataSet, bool locked) + internal DataViewManager(DataSet? dataSet, bool locked) { GC.SuppressFinalize(this); _dataSet = dataSet; @@ -38,7 +39,8 @@ namespace System.Data } [DefaultValue(null)] - public DataSet DataSet + [DisallowNull] + public DataSet? DataSet { get { return _dataSet; } set @@ -119,15 +121,15 @@ namespace System.Data string table = XmlConvert.DecodeName(r.LocalName); if (r.MoveToAttribute("Sort")) { - _dataViewSettingsCollection[table].Sort = r.Value; + _dataViewSettingsCollection[table]!.Sort = r.Value; } if (r.MoveToAttribute("RowFilter")) { - _dataViewSettingsCollection[table].RowFilter = r.Value; + _dataViewSettingsCollection[table]!.RowFilter = r.Value; } if (r.MoveToAttribute("RowStateFilter")) { - _dataViewSettingsCollection[table].RowStateFilter = (DataViewRowState)Enum.Parse(typeof(DataViewRowState), r.Value); + _dataViewSettingsCollection[table]!.RowStateFilter = (DataViewRowState)Enum.Parse(typeof(DataViewRowState), r.Value); } } } @@ -155,13 +157,13 @@ namespace System.Data array.SetValue(new DataViewManagerListItemTypeDescriptor(this), index); } - object IList.this[int index] + object? IList.this[int index] { get { return _item; } set { throw ExceptionBuilder.CannotModifyCollection(); } } - int IList.Add(object value) + int IList.Add(object? value) { throw ExceptionBuilder.CannotModifyCollection(); } @@ -171,16 +173,16 @@ namespace System.Data throw ExceptionBuilder.CannotModifyCollection(); } - bool IList.Contains(object value) => (value == _item); + bool IList.Contains(object? value) => (value == _item); - int IList.IndexOf(object value) => (value == _item) ? 1 : -1; + int IList.IndexOf(object? value) => (value == _item) ? 1 : -1; - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { throw ExceptionBuilder.CannotModifyCollection(); } - void IList.Remove(object value) + void IList.Remove(object? value) { throw ExceptionBuilder.CannotModifyCollection(); } @@ -223,7 +225,7 @@ namespace System.Data get { throw s_notSupported; } } - public event System.ComponentModel.ListChangedEventHandler ListChanged; + public event System.ComponentModel.ListChangedEventHandler? ListChanged; void IBindingList.AddIndex(PropertyDescriptor property) { @@ -253,7 +255,7 @@ namespace System.Data // SDUB: GetListName and GetItemProperties almost the same in DataView and DataViewManager string System.ComponentModel.ITypedList.GetListName(PropertyDescriptor[] listAccessors) { - DataSet dataSet = DataSet; + DataSet? dataSet = DataSet; if (dataSet == null) { throw ExceptionBuilder.CanNotUseDataViewManager(); @@ -265,7 +267,7 @@ namespace System.Data } else { - DataTable table = dataSet.FindTable(null, listAccessors, 0); + DataTable? table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { return table.TableName; @@ -276,7 +278,7 @@ namespace System.Data PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { - DataSet dataSet = DataSet; + DataSet? dataSet = DataSet; if (dataSet == null) { throw ExceptionBuilder.CanNotUseDataViewManager(); @@ -288,7 +290,7 @@ namespace System.Data } else { - DataTable table = dataSet.FindTable(null, listAccessors, 0); + DataTable? table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { return table.GetPropertyDescriptorCollection(null); @@ -324,23 +326,23 @@ namespace System.Data protected virtual void TableCollectionChanged(object sender, CollectionChangeEventArgs e) { - PropertyDescriptor NullProp = null; + PropertyDescriptor? NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataTablePropertyDescriptor((System.Data.DataTable)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataTablePropertyDescriptor((System.Data.DataTable)e.Element)) : - /*default*/ null + /*default*/ null! // TODO: This is very likely wrong ); } protected virtual void RelationCollectionChanged(object sender, CollectionChangeEventArgs e) { - DataRelationPropertyDescriptor NullProp = null; + DataRelationPropertyDescriptor? NullProp = null; OnListChanged( e.Action == CollectionChangeAction.Add ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorAdded, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : e.Action == CollectionChangeAction.Refresh ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorChanged, NullProp) : e.Action == CollectionChangeAction.Remove ? new ListChangedEventArgs(ListChangedType.PropertyDescriptorDeleted, new DataRelationPropertyDescriptor((System.Data.DataRelation)e.Element)) : - /*default*/ null + /*default*/ null! // TODO: This is very likely wrong ); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs index c692701..24059e6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewManagerListItemTypeDescriptor.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable + using System.ComponentModel; namespace System.Data diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs index 808d426..2ec0f4f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewSetting.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; namespace System.Data { [TypeConverter((typeof(ExpandableObjectConverter)))] public class DataViewSetting { - private DataViewManager _dataViewManager; - private DataTable _table; + private DataViewManager? _dataViewManager; + private DataTable? _table; private string _sort = string.Empty; private string _rowFilter = string.Empty; private DataViewRowState _rowStateFilter = DataViewRowState.CurrentRows; @@ -30,7 +31,7 @@ namespace System.Data } [Browsable(false)] - public DataViewManager DataViewManager => _dataViewManager; + public DataViewManager? DataViewManager => _dataViewManager; internal void SetDataViewManager(DataViewManager dataViewManager) { @@ -41,7 +42,7 @@ namespace System.Data } [Browsable(false)] - public DataTable Table => _table; + public DataTable? Table => _table; internal void SetDataTable(DataTable table) { @@ -51,6 +52,7 @@ namespace System.Data } } + [AllowNull] public string RowFilter { get { return _rowFilter; } @@ -80,6 +82,7 @@ namespace System.Data } } + [AllowNull] public string Sort { get { return _sort; } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs index c2b3cad..dc059c1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewSettingCollection.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -28,7 +29,7 @@ namespace System.Data { throw ExceptionBuilder.ArgumentNull(nameof(table)); } - DataViewSetting dataViewSetting = (DataViewSetting)_list[table]; + DataViewSetting? dataViewSetting = (DataViewSetting?)_list[table]; if (dataViewSetting == null) { dataViewSetting = new DataViewSetting(); @@ -48,10 +49,10 @@ namespace System.Data } } - private DataTable GetTable(string tableName) + private DataTable? GetTable(string tableName) { - DataTable dt = null; - DataSet ds = _dataViewManager.DataSet; + DataTable? dt = null; + DataSet? ds = _dataViewManager.DataSet; if (ds != null) { dt = ds.Tables[tableName]; @@ -59,10 +60,10 @@ namespace System.Data return dt; } - private DataTable GetTable(int index) + private DataTable? GetTable(int index) { - DataTable dt = null; - DataSet ds = _dataViewManager.DataSet; + DataTable? dt = null; + DataSet? ds = _dataViewManager.DataSet; if (ds != null) { dt = ds.Tables[index]; @@ -70,11 +71,11 @@ namespace System.Data return dt; } - public virtual DataViewSetting this[string tableName] + public virtual DataViewSetting? this[string tableName] { get { - DataTable dt = GetTable(tableName); + DataTable? dt = GetTable(tableName); if (dt != null) { return this[dt]; @@ -83,11 +84,12 @@ namespace System.Data } } + [MaybeNull] public virtual DataViewSetting this[int index] { get { - DataTable dt = GetTable(index); + DataTable? dt = GetTable(index); if (dt != null) { return this[dt]; @@ -96,7 +98,7 @@ namespace System.Data } set { - DataTable dt = GetTable(index); + DataTable? dt = GetTable(index); if (dt != null) { this[dt] = value; @@ -127,7 +129,7 @@ namespace System.Data { get { - DataSet ds = _dataViewManager.DataSet; + DataSet? ds = _dataViewManager.DataSet; return (ds == null) ? 0 : ds.Tables.Count; } } @@ -154,15 +156,15 @@ namespace System.Data private sealed class DataViewSettingsEnumerator : IEnumerator { - private readonly DataViewSettingCollection _dataViewSettings; + private readonly DataViewSettingCollection? _dataViewSettings; private readonly IEnumerator _tableEnumerator; public DataViewSettingsEnumerator(DataViewManager dvm) { - DataSet ds = dvm.DataSet; + DataSet? ds = dvm.DataSet; if (ds != null) { _dataViewSettings = dvm.DataViewSettings; - _tableEnumerator = dvm.DataSet.Tables.GetEnumerator(); + _tableEnumerator = dvm.DataSet!.Tables.GetEnumerator(); } else { @@ -174,7 +176,7 @@ namespace System.Data public void Reset() => _tableEnumerator.Reset(); - public object Current => _dataViewSettings[(DataTable)_tableEnumerator.Current]; + public object Current => _dataViewSettings![(DataTable)_tableEnumerator.Current]; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs index 0639f0d..7e2edf3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs @@ -19,6 +19,8 @@ namespace System.Data { } +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) @@ -58,5 +60,6 @@ namespace System.Data return base.ConvertFrom(context, culture, value); } +#nullable enable } } diff --git a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs index cf05d59..bbdf6b5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollection.cs @@ -15,7 +15,7 @@ namespace System.Data public abstract class EnumerableRowCollection : IEnumerable { internal abstract Type ElementType { get; } - internal abstract DataTable Table { get; } + internal abstract DataTable? Table { get; } internal EnumerableRowCollection() { @@ -23,7 +23,7 @@ namespace System.Data IEnumerator IEnumerable.GetEnumerator() { - return null; + return null!; } } @@ -32,14 +32,14 @@ namespace System.Data /// public class EnumerableRowCollection : EnumerableRowCollection, IEnumerable { - private readonly DataTable _table; + private readonly DataTable? _table; private readonly IEnumerable _enumerableRows; private readonly List> _listOfPredicates; // Stores list of sort expression in the order provided by user. E.g. order by, thenby, thenby descending.. private readonly SortExpressionBuilder _sortExpression; - private readonly Func _selector; + private readonly Func? _selector; internal override Type ElementType { @@ -58,7 +58,7 @@ namespace System.Data } } - internal override DataTable Table + internal override DataTable? Table { get { @@ -70,7 +70,7 @@ namespace System.Data /// This constructor is used when Select operator is called with output Type other than input row Type. /// Basically fail on GetLDV(), but other LINQ operators must work. /// - internal EnumerableRowCollection(IEnumerable enumerableRows, bool isDataViewable, DataTable table) + internal EnumerableRowCollection(IEnumerable enumerableRows, bool isDataViewable, DataTable? table) { Debug.Assert(!isDataViewable || table != null, "isDataViewable bug table is null"); @@ -98,7 +98,7 @@ namespace System.Data /// Copy Constructor that sets the input IEnumerable as enumerableRows /// Used to maintain IEnumerable that has linq operators executed in the same order as the user /// - internal EnumerableRowCollection(EnumerableRowCollection source, IEnumerable enumerableRows, Func selector) + internal EnumerableRowCollection(EnumerableRowCollection? source, IEnumerable enumerableRows, Func? selector) { Debug.Assert(null != enumerableRows, "null enumerableRows"); @@ -148,11 +148,11 @@ namespace System.Data throw DataSetUtil.NotSupported(SR.ToLDVUnsupported); } - LinqDataView view = null; + LinqDataView? view = null; #region BuildSinglePredicate - Func finalPredicate = null; // Conjunction of all .Where(..) predicates + Func? finalPredicate = null; // Conjunction of all .Where(..) predicates if ((null != _selector) && (0 < _listOfPredicates.Count)) { // Hook up all individual predicates into one predicate @@ -299,7 +299,7 @@ namespace System.Data _sortExpression.Add( delegate (TRow input) { - return keySelector(input); + return keySelector(input)!; }, delegate (object val1, object val2) { diff --git a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs index d3872b3..54f875b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/EnumerableRowCollectionExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics; using System.Linq; namespace System.Data @@ -149,6 +150,8 @@ namespace System.Data //Anonymous type or some other type //The only thing that matters from this point on is _enumerableRows + Debug.Assert(source != null); + IEnumerable typedEnumerable = Enumerable.Cast(source); EnumerableRowCollection newEdt = new EnumerableRowCollection( diff --git a/src/libraries/System.Data.Common/src/System/Data/FillErrorEventArgs.cs b/src/libraries/System.Data.Common/src/System/Data/FillErrorEventArgs.cs index 1e5f266..ee6282d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/FillErrorEventArgs.cs +++ b/src/libraries/System.Data.Common/src/System/Data/FillErrorEventArgs.cs @@ -6,18 +6,14 @@ namespace System.Data public class FillErrorEventArgs : EventArgs { private bool _continueFlag; - private readonly DataTable _dataTable; - private Exception _errors; - private readonly object[] _values; + private readonly DataTable? _dataTable; + private Exception? _errors; + private readonly object?[] _values; - public FillErrorEventArgs(DataTable dataTable, object[] values) + public FillErrorEventArgs(DataTable? dataTable, object?[]? values) { _dataTable = dataTable; - _values = values; - if (null == _values) - { - _values = Array.Empty(); - } + _values = values ?? Array.Empty(); } public bool Continue @@ -26,19 +22,19 @@ namespace System.Data set { _continueFlag = value; } } - public DataTable DataTable => _dataTable; + public DataTable? DataTable => _dataTable; - public Exception Errors + public Exception? Errors { get { return _errors; } set { _errors = value; } } - public object[] Values + public object?[] Values { get { - object[] copy = new object[_values.Length]; + object?[] copy = new object?[_values.Length]; for (int i = 0; i < _values.Length; ++i) { copy[i] = _values[i]; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs index 09d7aab..98760f2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs @@ -24,21 +24,21 @@ namespace System.Data private readonly Aggregate _aggregate; private readonly bool _local; // set to true if the aggregate calculated locally (for the current table) - private readonly string _relationName; + private readonly string? _relationName; private readonly string _columnName; // CONSIDER PERF: keep the objects, not names. // ? try to drop a column - private DataTable _childTable; - private DataColumn _column; - private DataRelation _relation; + private DataTable? _childTable; + private DataColumn? _column; + private DataRelation? _relation; - internal AggregateNode(DataTable table, FunctionId aggregateType, string columnName) : + internal AggregateNode(DataTable? table, FunctionId aggregateType, string columnName) : this(table, aggregateType, columnName, true, null) { } - internal AggregateNode(DataTable table, FunctionId aggregateType, string columnName, bool local, string relationName) : base(table) + internal AggregateNode(DataTable? table, FunctionId aggregateType, string columnName, bool local, string? relationName) : base(table) { Debug.Assert(columnName != null, "Invalid parameter column name (null)."); _aggregate = (Aggregate)(int)aggregateType; @@ -70,7 +70,7 @@ namespace System.Data { BindTable(table); if (table == null) - throw ExprException.AggregateUnbound(ToString()); + throw ExprException.AggregateUnbound(ToString()!); if (_local) { @@ -87,7 +87,7 @@ namespace System.Data if (relations.Count > 1) { - throw ExprException.UnresolvedRelation(table.TableName, ToString()); + throw ExprException.UnresolvedRelation(table.TableName, ToString()!); } if (relations.Count == 1) { @@ -95,7 +95,7 @@ namespace System.Data } else { - throw ExprException.AggregateUnbound(ToString()); + throw ExprException.AggregateUnbound(ToString()!); } } else @@ -133,7 +133,7 @@ namespace System.Data AggregateNode.Bind(_relation, list); } - internal static void Bind(DataRelation relation, List list) + internal static void Bind(DataRelation? relation, List list) { if (null != relation) { @@ -160,10 +160,10 @@ namespace System.Data return Eval(null, DataRowVersion.Default); } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { if (_childTable == null) - throw ExprException.AggregateUnbound(ToString()); + throw ExprException.AggregateUnbound(ToString()!); DataRow[] rows; @@ -180,7 +180,7 @@ namespace System.Data } if (_relation == null) { - throw ExprException.AggregateUnbound(ToString()); + throw ExprException.AggregateUnbound(ToString()!); } rows = row.GetChildRows(_relation, version); } @@ -216,19 +216,19 @@ namespace System.Data } records = recordList.ToArray(); - return _column.GetAggregateValue(records, _type); + return _column!.GetAggregateValue(records, _type); } // Helper for the DataTable.Compute method internal override object Eval(int[] records) { if (_childTable == null) - throw ExprException.AggregateUnbound(ToString()); + throw ExprException.AggregateUnbound(ToString()!); if (!_local) { - throw ExprException.ComputeNotAggregate(ToString()); + throw ExprException.ComputeNotAggregate(ToString()!); } - return _column.GetAggregateValue(records, _type); + return _column!.GetAggregateValue(records, _type); } internal override bool IsConstant() @@ -257,9 +257,9 @@ namespace System.Data { return true; } - if (_column.Computed) + if (_column!.Computed) { - return _column.DataExpression.DependsOn(column); + return _column.DataExpression!.DependsOn(column); } return false; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs index 36deed2..fb537bd 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs @@ -16,7 +16,7 @@ namespace System.Data internal ExpressionNode _left; internal ExpressionNode _right; - internal BinaryNode(DataTable table, int op, ExpressionNode left, ExpressionNode right) : base(table) + internal BinaryNode(DataTable? table, int op, ExpressionNode left, ExpressionNode right) : base(table) { _op = op; _left = left; @@ -35,7 +35,7 @@ namespace System.Data return Eval(null, DataRowVersion.Default); } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { return EvalBinaryOp(_op, _left, _right, row, version, null); } @@ -123,7 +123,7 @@ namespace System.Data else return new ZeroOpNode(Operators.False); } - return new ConstNode(table, ValueType.Object, val, false); + return new ConstNode(table!, ValueType.Object, val, false); } else return this; @@ -134,7 +134,7 @@ namespace System.Data throw ExprException.TypeMismatchInBinop(op, left, right); } - private static object Eval(ExpressionNode expr, DataRow row, DataRowVersion version, int[] recordNos) + private static object Eval(ExpressionNode expr, DataRow? row, DataRowVersion version, int[]? recordNos) { if (recordNos == null) { @@ -151,7 +151,7 @@ namespace System.Data return BinaryCompare(vLeft, vRight, resultType, op, null); } - internal int BinaryCompare(object vLeft, object vRight, StorageType resultType, int op, CompareInfo comparer) + internal int BinaryCompare(object vLeft, object vRight, StorageType resultType, int op, CompareInfo? comparer) { int result = 0; try @@ -183,7 +183,7 @@ namespace System.Data // DTO can only be compared to DTO, other cases: cast Exception return DateTimeOffset.Compare((DateTimeOffset)vLeft, (DateTimeOffset)vRight); case StorageType.String: - return table.Compare(Convert.ToString(vLeft, FormatProvider), Convert.ToString(vRight, FormatProvider), comparer); + return table!.Compare(Convert.ToString(vLeft, FormatProvider)!, Convert.ToString(vRight, FormatProvider)!, comparer); case StorageType.Guid: return ((Guid)vLeft).CompareTo((Guid)vRight); case StorageType.Boolean: @@ -220,7 +220,7 @@ namespace System.Data case StorageType.SqlSingle: return SqlConvert.ConvertToSqlSingle(vLeft).CompareTo(SqlConvert.ConvertToSqlSingle(vRight)); case StorageType.SqlString: - return table.Compare(vLeft.ToString(), vRight.ToString()); + return table!.Compare(vLeft.ToString()!, vRight.ToString()!); case StorageType.SqlGuid: return ((SqlGuid)vLeft).CompareTo(vRight); case StorageType.SqlBoolean: @@ -267,7 +267,7 @@ namespace System.Data return result; } - private object EvalBinaryOp(int op, ExpressionNode left, ExpressionNode right, DataRow row, DataRowVersion version, int[] recordNos) + private object EvalBinaryOp(int op, ExpressionNode left, ExpressionNode right, DataRow? row, DataRowVersion version, int[]? recordNos) { object vLeft; object vRight; @@ -1090,8 +1090,7 @@ namespace System.Data for (int i = 0; i < into._argumentCount; i++) { - vRight = into._arguments[i].Eval(); - + vRight = into._arguments![i].Eval(); if ((vRight == DBNull.Value) || (right.IsSqlColumn && DataStorage.IsObjectSqlNull(vRight))) continue; @@ -1508,14 +1507,14 @@ namespace System.Data private static readonly char[] s_trimChars = new char[] { (char)0x20, (char)0x3000 }; private int _kind; - private string _pattern; + private string? _pattern; - internal LikeNode(DataTable table, int op, ExpressionNode left, ExpressionNode right) + internal LikeNode(DataTable? table, int op, ExpressionNode left, ExpressionNode right) : base(table, op, left, right) { } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { object vLeft = _left.Eval(row, version); string substring; @@ -1564,14 +1563,14 @@ namespace System.Data case match_all: return true; case match_exact: - return (0 == table.Compare(s1, substring)); + return (0 == table!.Compare(s1, substring)); case match_middle: - return (0 <= table.IndexOf(s1, substring)); + return (0 <= table!.IndexOf(s1, substring)); case match_left: - return (0 == table.IndexOf(s1, substring)); + return (0 == table!.IndexOf(s1, substring)); case match_right: string s2 = substring.TrimEnd(s_trimChars); - return table.IsSuffix(s1, s2); + return table!.IsSuffix(s1, s2); default: Debug.Fail("Unexpected LIKE kind"); return DBNull.Value; @@ -1584,7 +1583,7 @@ namespace System.Data char[] patchars = new char[length + 1]; pat.CopyTo(0, patchars, 0, length); patchars[length] = (char)0; - string substring = null; + string? substring = null; char[] constchars = new char[length + 1]; int newLength = 0; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs index 95eec4a..63d3676 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs @@ -11,11 +11,11 @@ namespace System.Data { internal readonly object _val; - internal ConstNode(DataTable table, ValueType type, object constant) : this(table, type, constant, true) + internal ConstNode(DataTable? table, ValueType type, object constant) : this(table, type, constant, true) { } - internal ConstNode(DataTable table, ValueType type, object constant, bool fParseQuotes) : base(table) + internal ConstNode(DataTable? table, ValueType type, object constant, bool fParseQuotes) : base(table) { switch (type) { @@ -73,7 +73,7 @@ namespace System.Data return _val; } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { return Eval(); } @@ -115,7 +115,7 @@ namespace System.Data } else { - string sval = (constant as string); + string? sval = (constant as string); if (null != sval) { decimal r12; @@ -132,7 +132,7 @@ namespace System.Data } else { - IConvertible convertible = (constant as IConvertible); + IConvertible? convertible = (constant as IConvertible); if (null != convertible) { try @@ -189,7 +189,7 @@ namespace System.Data } else { - string sval = (constant as string); + string? sval = (constant as string); if (null != sval) { int i4; @@ -210,7 +210,7 @@ namespace System.Data } else { - IConvertible convertible = (constant as IConvertible); + IConvertible? convertible = (constant as IConvertible); if (null != convertible) { try diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs index 62d40a3..8be3afb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs @@ -10,21 +10,21 @@ namespace System.Data { internal sealed class DataExpression : IFilter { - internal string _originalExpression; // original, unoptimized string + internal string? _originalExpression; // original, unoptimized string private readonly bool _parsed; private bool _bound; - private ExpressionNode _expr; - private DataTable _table; + private ExpressionNode? _expr; + private DataTable? _table; private readonly StorageType _storageType; - private readonly Type _dataType; // This set if the expression is part of ExpressionCoulmn + private readonly Type? _dataType; // This set if the expression is part of ExpressionCoulmn private DataColumn[] _dependency = Array.Empty(); - internal DataExpression(DataTable table, string expression) : this(table, expression, null) + internal DataExpression(DataTable? table, string? expression) : this(table, expression, null) { } - internal DataExpression(DataTable table, string expression, Type type) + internal DataExpression(DataTable? table, string? expression, Type? type) { ExpressionParser parser = new ExpressionParser(table); parser.LoadExpression(expression); @@ -32,12 +32,13 @@ namespace System.Data _originalExpression = expression; _expr = null; + // Note: nobody seems to pass a null expression in the codebase if (expression != null) { _storageType = DataStorage.GetStorageType(type); if (_storageType == StorageType.BigInteger) { - throw ExprException.UnsupportedDataType(type); + throw ExprException.UnsupportedDataType(type!); } _dataType = type; @@ -62,7 +63,7 @@ namespace System.Data } } - internal ExpressionNode ExpressionNode + internal ExpressionNode? ExpressionNode { get { @@ -78,7 +79,7 @@ namespace System.Data } } - internal void Bind(DataTable table) + internal void Bind(DataTable? table) { _table = table; @@ -111,17 +112,18 @@ namespace System.Data internal object Evaluate() { - return Evaluate((DataRow)null, DataRowVersion.Default); + return Evaluate((DataRow?)null, DataRowVersion.Default); } - internal object Evaluate(DataRow row, DataRowVersion version) + internal object Evaluate(DataRow? row, DataRowVersion version) { - object result; + object? result; if (!_bound) { Bind(_table); } + // Note: _expr is always non-null in the current codebase if (_expr != null) { result = _expr.Eval(row, version); @@ -133,13 +135,14 @@ namespace System.Data { if (StorageType.Object != _storageType) { - result = SqlConvert.ChangeType2(result, _storageType, _dataType, _table.FormatProvider); + // TODO: _dataType can be null, probably a bug + result = SqlConvert.ChangeType2(result, _storageType, _dataType!, _table!.FormatProvider); } } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); - throw ExprException.DatavalueConvertion(result, _dataType, e); + throw ExprException.DatavalueConvertion(result, _dataType!, e); } } } @@ -147,7 +150,7 @@ namespace System.Data { result = null; } - return result; + return result!; } internal object Evaluate(DataRow[] rows) diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionNode.cs index cf92bce..2febaeb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionNode.cs @@ -8,9 +8,9 @@ namespace System.Data { internal abstract class ExpressionNode { - private DataTable _table; + private DataTable? _table; - protected ExpressionNode(DataTable table) + protected ExpressionNode(DataTable? table) { _table = table; } @@ -31,7 +31,7 @@ namespace System.Data } } - protected DataTable table + protected DataTable? table { get { return _table; } } @@ -44,7 +44,7 @@ namespace System.Data internal abstract void Bind(DataTable table, List list); internal abstract object Eval(); - internal abstract object Eval(DataRow row, DataRowVersion version); + internal abstract object Eval(DataRow? row, DataRowVersion version); internal abstract object Eval(int[] recordNos); internal abstract bool IsConstant(); internal abstract bool IsTableConstant(); diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs index 227f405..d6e20b5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs @@ -95,7 +95,7 @@ namespace System.Data private readonly char _exponentL = 'e'; private readonly char _exponentU = 'E'; - internal char[] _text; + internal char[] _text = default!; // Always initialized in LoadExpression before use internal int _pos; internal int _start; internal Tokens _token; @@ -105,21 +105,21 @@ namespace System.Data internal int _topOperator; internal int _topNode; - private readonly DataTable _table; + private readonly DataTable? _table; private const int MaxPredicates = 100; internal ExpressionNode[] _nodeStack = new ExpressionNode[MaxPredicates]; internal int _prevOperand; - internal ExpressionNode _expression; + internal ExpressionNode? _expression; - internal ExpressionParser(DataTable table) + internal ExpressionParser(DataTable? table) { _table = table; } - internal void LoadExpression(string data) + internal void LoadExpression(string? data) { int length; @@ -205,8 +205,8 @@ namespace System.Data case Tokens.Float: case Tokens.StringConst: case Tokens.Date: - ExpressionNode node = null; - string str = null; + ExpressionNode? node = null; + string? str = null; /* Constants and identifiers: create leaf node */ @@ -233,7 +233,7 @@ namespace System.Data switch (_token) { case Tokens.Parent: - string relname; + string? relname; string colname; // parsing Parent[(relation_name)].column_name) @@ -345,7 +345,7 @@ namespace System.Data BuildExpression(Operators.priProc); _prevOperand = Empty; - ExpressionNode nodebefore = NodePeek(); + ExpressionNode? nodebefore = NodePeek(); if (nodebefore == null || nodebefore.GetType() != typeof(NameNode)) { @@ -413,7 +413,7 @@ namespace System.Data ExpressionNode argument = NodePop(); /* Get the procedure name and append argument */ - Debug.Assert(_topNode > 0 && NodePeek().GetType() == typeof(FunctionNode), "The function node should be created on '('"); + Debug.Assert(_topNode > 0 && NodePeek()!.GetType() == typeof(FunctionNode), "The function node should be created on '('"); FunctionNode func = (FunctionNode)NodePop(); func.AddArgument(argument); @@ -525,7 +525,7 @@ namespace System.Data case Tokens.Dot: //if there is a name on the stack append it. - ExpressionNode before = NodePeek(); + ExpressionNode? before = NodePeek(); if (before != null && before.GetType() == typeof(NameNode)) { @@ -563,7 +563,7 @@ namespace System.Data Debug.Assert(_token == Tokens.LeftParen, "ParseAggregateArgument(): Invalid argument, token <> '('"); bool child; - string relname; + string? relname; string colname; Scan(); @@ -625,7 +625,7 @@ namespace System.Data /// /// NodePeek - Peek at the top node. /// - private ExpressionNode NodePeek() + private ExpressionNode? NodePeek() { if (_topNode <= 0) return null; @@ -654,7 +654,7 @@ namespace System.Data private void BuildExpression(int pri) { - ExpressionNode expr = null; + ExpressionNode? expr = null; Debug.Assert(pri > Operators.priStart && pri <= Operators.priMax, "Invalid priority value"); @@ -671,7 +671,7 @@ namespace System.Data Debug.Assert(opInfo._priority >= pri, "Invalid prioriry value"); _topOperator--; - ExpressionNode nodeLeft; + ExpressionNode? nodeLeft; ExpressionNode nodeRight; switch (opInfo._type) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs index a23c95c..cf277ee 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs @@ -17,9 +17,9 @@ namespace System.Data } public InvalidExpressionException() : base() { } - public InvalidExpressionException(string s) : base(s) { } + public InvalidExpressionException(string? s) : base(s) { } - public InvalidExpressionException(string message, Exception innerException) : base(message, innerException) { } + public InvalidExpressionException(string? message, Exception? innerException) : base(message, innerException) { } } [Serializable] @@ -32,9 +32,9 @@ namespace System.Data } public EvaluateException() : base() { } - public EvaluateException(string s) : base(s) { } + public EvaluateException(string? s) : base(s) { } - public EvaluateException(string message, Exception innerException) : base(message, innerException) { } + public EvaluateException(string? message, Exception? innerException) : base(message, innerException) { } } [Serializable] @@ -47,9 +47,9 @@ namespace System.Data } public SyntaxErrorException() : base() { } - public SyntaxErrorException(string s) : base(s) { } + public SyntaxErrorException(string? s) : base(s) { } - public SyntaxErrorException(string message, Exception innerException) : base(message, innerException) { } + public SyntaxErrorException(string? message, Exception? innerException) : base(message, innerException) { } } internal sealed class ExprException @@ -80,7 +80,7 @@ namespace System.Data ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } - private static EvaluateException _Eval(string error, Exception innerException) + private static EvaluateException _Eval(string error, Exception? innerException) { EvaluateException e = new EvaluateException(error/*, innerException*/); ExceptionBuilder.TraceExceptionAsReturnValue(e); @@ -169,7 +169,7 @@ namespace System.Data return _Eval(SR.Format(SR.Expr_DatatypeConvertion, type1.ToString(), type2.ToString())); } - public static Exception DatavalueConvertion(object value, Type type, Exception innerException) + public static Exception DatavalueConvertion(object value, Type type, Exception? innerException) { return _Eval(SR.Format(SR.Expr_DatavalueConvertion, value.ToString(), type.ToString()), innerException); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs index 22584bc..f251503 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs @@ -14,7 +14,7 @@ namespace System.Data internal readonly int _info = -1; internal int _argumentCount; internal const int initialCapacity = 1; - internal ExpressionNode[] _arguments; + internal ExpressionNode[]? _arguments; private static readonly Function[] s_funcs = new Function[] { new Function("Abs", FunctionId.Abs, typeof(object), true, false, 1, typeof(object), null, null), @@ -37,7 +37,7 @@ namespace System.Data new Function("Avg", FunctionId.Avg, typeof(object), false, false, 1, null, null, null), }; - internal FunctionNode(DataTable table, string name) : base(table) + internal FunctionNode(DataTable? table, string name) : base(table) { _name = name; for (int i = 0; i < s_funcs.Length; i++) @@ -84,7 +84,7 @@ namespace System.Data { if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); - _arguments[0].Bind(table, list); + _arguments![0].Bind(table, list); if (_arguments[1].GetType() == typeof(NameNode)) { @@ -97,7 +97,7 @@ namespace System.Data { for (int i = 0; i < _argumentCount; i++) { - _arguments[i].Bind(table, list); + _arguments![i].Bind(table, list); } } } @@ -107,7 +107,7 @@ namespace System.Data return Eval(null, DataRowVersion.Default); } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { Debug.Assert(_info < s_funcs.Length && _info >= 0, "Invalid function info."); @@ -121,14 +121,14 @@ namespace System.Data if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); - argumentValues[0] = _arguments[0].Eval(row, version); + argumentValues[0] = _arguments![0].Eval(row, version); argumentValues[1] = GetDataType(_arguments[1]); } else if (s_funcs[_info]._id != FunctionId.Iif) { // We do not want to evaluate arguments of IIF, we will already do it in EvalFunction/ second point: we may go to div by 0 for (int i = 0; i < _argumentCount; i++) { - argumentValues[i] = _arguments[i].Eval(row, version); + argumentValues[i] = _arguments![i].Eval(row, version); if (s_funcs[_info]._isValidateArguments) { @@ -151,12 +151,12 @@ namespace System.Data { if ((typeof(string) != (argumentValues[i].GetType())) && (typeof(SqlString) != (argumentValues[i].GetType()))) { - throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]); + throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]!); } } else { - throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]); + throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]!); } } } @@ -167,7 +167,7 @@ namespace System.Data internal override object Eval(int[] recordNos) { - throw ExprException.ComputeNotAggregate(ToString()); + throw ExprException.ComputeNotAggregate(ToString()!); } internal override bool IsConstant() @@ -180,7 +180,7 @@ namespace System.Data for (int i = 0; i < _argumentCount; i++) { - constant = constant && _arguments[i].IsConstant(); + constant = constant && _arguments![i].IsConstant(); } Debug.Assert(_info > -1, "All function nodes should be bound at this point."); // default info is -1, it means if not bounded, it should be -1, not 0!! @@ -192,7 +192,7 @@ namespace System.Data { for (int i = 0; i < _argumentCount; i++) { - if (!_arguments[i].IsTableConstant()) + if (!_arguments![i].IsTableConstant()) { return false; } @@ -204,7 +204,7 @@ namespace System.Data { for (int i = 0; i < _argumentCount; i++) { - if (_arguments[i].HasLocalAggregate()) + if (_arguments![i].HasLocalAggregate()) { return true; } @@ -216,7 +216,7 @@ namespace System.Data { for (int i = 0; i < _argumentCount; i++) { - if (_arguments[i].HasRemoteAggregate()) + if (_arguments![i].HasRemoteAggregate()) { return true; } @@ -228,7 +228,7 @@ namespace System.Data { for (int i = 0; i < _argumentCount; i++) { - if (_arguments[i].DependsOn(column)) + if (_arguments![i].DependsOn(column)) return true; } return false; @@ -238,7 +238,7 @@ namespace System.Data { for (int i = 0; i < _argumentCount; i++) { - _arguments[i] = _arguments[i].Optimize(); + _arguments![i] = _arguments[i].Optimize(); } Debug.Assert(_info > -1, "Optimizing unbound function "); // default info is -1, it means if not bounded, it should be -1, not 0!! @@ -265,7 +265,7 @@ namespace System.Data private Type GetDataType(ExpressionNode node) { Type nodeType = node.GetType(); - string typeName = null; + string? typeName = null; if (nodeType == typeof(NameNode)) { @@ -281,7 +281,7 @@ namespace System.Data throw ExprException.ArgumentType(s_funcs[_info]._name, 2, typeof(Type)); } - Type dataType = Type.GetType(typeName); + Type? dataType = Type.GetType(typeName); if (dataType == null) { @@ -291,7 +291,7 @@ namespace System.Data return dataType; } - private object EvalFunction(FunctionId id, object[] argumentValues, DataRow row, DataRowVersion version) + private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row, DataRowVersion version) { StorageType storageType; switch (id) @@ -333,7 +333,7 @@ namespace System.Data case FunctionId.cStr: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); - return Convert.ToString(argumentValues[0], FormatProvider); + return Convert.ToString(argumentValues[0], FormatProvider)!; case FunctionId.Charindex: Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); @@ -355,7 +355,7 @@ namespace System.Data case FunctionId.Iif: Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); - object first = _arguments[0].Eval(row, version); + object first = _arguments![0].Eval(row, version); if (DataExpression.ToBoolean(first) != false) { @@ -639,19 +639,20 @@ namespace System.Data internal readonly bool _isValidateArguments; internal readonly bool _isVariantArgumentList; internal readonly int _argumentCount; - internal readonly Type[] _parameters = new Type[] { null, null, null }; + internal readonly Type?[] _parameters = new Type?[] { null, null, null }; + // TODO: Unused, consider removing internal Function() { - _name = null; + _name = null!; _id = FunctionId.none; - _result = null; + _result = null!; _isValidateArguments = false; _argumentCount = 0; } internal Function(string name, FunctionId id, Type result, bool IsValidateArguments, - bool IsVariantArgumentList, int argumentCount, Type a1, Type a2, Type a3) + bool IsVariantArgumentList, int argumentCount, Type? a1, Type? a2, Type? a3) { _name = name; _id = id; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs index b27a864..bacf6d2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/LookupNode.cs @@ -8,13 +8,13 @@ namespace System.Data { internal sealed class LookupNode : ExpressionNode { - private readonly string _relationName; // can be null + private readonly string? _relationName; // can be null private readonly string _columnName; - private DataColumn _column; - private DataRelation _relation; + private DataColumn? _column; + private DataRelation? _relation; - internal LookupNode(DataTable table, string columnName, string relationName) : base(table) + internal LookupNode(DataTable? table, string columnName, string? relationName) : base(table) { _relationName = relationName; _columnName = columnName; @@ -27,7 +27,7 @@ namespace System.Data _relation = null; if (table == null) - throw ExprException.ExpressionUnbound(ToString()); + throw ExprException.ExpressionUnbound(ToString()!); // First find parent table @@ -40,7 +40,7 @@ namespace System.Data if (relations.Count > 1) { - throw ExprException.UnresolvedRelation(table.TableName, ToString()); + throw ExprException.UnresolvedRelation(table.TableName, ToString()!); } _relation = relations[0]; } @@ -50,7 +50,7 @@ namespace System.Data } if (null == _relation) { - throw ExprException.BindFailure(_relationName); // this operation is not clone specific, throw generic exception + throw ExprException.BindFailure(_relationName!); // this operation is not clone specific, throw generic exception } DataTable parentTable = _relation.ParentTable; @@ -87,12 +87,12 @@ namespace System.Data throw ExprException.EvalNoContext(); } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { if (_column == null || _relation == null) - throw ExprException.ExpressionUnbound(ToString()); + throw ExprException.ExpressionUnbound(ToString()!); - DataRow parent = row.GetParentRow(_relation, version); + DataRow? parent = row!.GetParentRow(_relation, version); if (parent == null) return DBNull.Value; @@ -101,7 +101,7 @@ namespace System.Data internal override object Eval(int[] recordNos) { - throw ExprException.ComputeNotAggregate(ToString()); + throw ExprException.ComputeNotAggregate(ToString()!); } internal override bool IsConstant() diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs index 9b18a94..8cb163d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs @@ -10,14 +10,14 @@ namespace System.Data { internal string _name; internal bool _found; - internal DataColumn _column; + internal DataColumn? _column; - internal NameNode(DataTable table, char[] text, int start, int pos) : base(table) + internal NameNode(DataTable? table, char[] text, int start, int pos) : base(table) { _name = ParseName(text, start, pos); } - internal NameNode(DataTable table, string name) : base(table) + internal NameNode(DataTable? table, string name) : base(table) { _name = name; } @@ -26,7 +26,7 @@ namespace System.Data { get { - return _column.IsSqlType; + return _column!.IsSqlType; } } @@ -81,7 +81,7 @@ namespace System.Data throw ExprException.EvalNoContext(); } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { if (!_found) { @@ -91,19 +91,19 @@ namespace System.Data if (row == null) { if (IsTableConstant()) // this column is TableConstant Aggregate Function - return _column.DataExpression.Evaluate(); + return _column!.DataExpression!.Evaluate(); else { throw ExprException.UnboundName(_name); } } - return _column[row.GetRecordFromVersion(version)]; + return _column![row.GetRecordFromVersion(version)]; } internal override object Eval(int[] records) { - throw ExprException.ComputeNotAggregate(ToString()); + throw ExprException.ComputeNotAggregate(ToString()!); } internal override bool IsConstant() @@ -115,7 +115,7 @@ namespace System.Data { if (_column != null && _column.Computed) { - return _column.DataExpression.IsTableAggregate(); + return _column.DataExpression!.IsTableAggregate(); } return false; } @@ -124,7 +124,7 @@ namespace System.Data { if (_column != null && _column.Computed) { - return _column.DataExpression.HasLocalAggregate(); + return _column.DataExpression!.HasLocalAggregate(); } return false; } @@ -133,7 +133,7 @@ namespace System.Data { if (_column != null && _column.Computed) { - return _column.DataExpression.HasRemoteAggregate(); + return _column.DataExpression!.HasRemoteAggregate(); } return false; } @@ -143,9 +143,9 @@ namespace System.Data if (_column == column) return true; - if (_column.Computed) + if (_column!.Computed) { - return _column.DataExpression.DependsOn(column); + return _column.DataExpression!.DependsOn(column); } return false; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs index 3da5dbc..3bff8db 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs @@ -14,7 +14,7 @@ namespace System.Data internal ExpressionNode _right; - internal UnaryNode(DataTable table, int op, ExpressionNode right) : base(table) + internal UnaryNode(DataTable? table, int op, ExpressionNode right) : base(table) { _op = op; _right = right; @@ -31,7 +31,7 @@ namespace System.Data return Eval(null, DataRowVersion.Default); } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { return EvalUnaryOp(_op, _right.Eval(row, version)); } @@ -59,7 +59,7 @@ namespace System.Data { return vl; } - throw ExprException.TypeMismatch(ToString()); + throw ExprException.TypeMismatch(ToString()!); case Operators.Negative: // the have to be better way for doing this.. @@ -118,7 +118,7 @@ namespace System.Data return value; } - throw ExprException.TypeMismatch(ToString()); + throw ExprException.TypeMismatch(ToString()!); case Operators.Not: if (vl is SqlBoolean) diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ZeroOpNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ZeroOpNode.cs index 07d5111..75291d3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ZeroOpNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ZeroOpNode.cs @@ -14,7 +14,6 @@ namespace System.Data internal const int zop_False = 0; internal const int zop_Null = -1; - internal ZeroOpNode(int op) : base(null) { _op = op; @@ -41,7 +40,7 @@ namespace System.Data } } - internal override object Eval(DataRow row, DataRowVersion version) + internal override object Eval(DataRow? row, DataRowVersion version) { return Eval(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs index 778dcae..058a2cf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs @@ -26,11 +26,11 @@ namespace System.Data private DataKey _parentKey; // Design time serialization - internal string _constraintName; - internal string[] _parentColumnNames; - internal string[] _childColumnNames; - internal string _parentTableName; - internal string _parentTableNamespace; + internal string? _constraintName; + internal string[]? _parentColumnNames; + internal string[]? _childColumnNames; + internal string? _parentTableName; + internal string? _parentTableNamespace; /// /// Initializes a new instance of the class with the specified parent and @@ -44,7 +44,7 @@ namespace System.Data /// Initializes a new instance of the class with the specified name, /// parent and child objects. /// - public ForeignKeyConstraint(string constraintName, DataColumn parentColumn, DataColumn childColumn) + public ForeignKeyConstraint(string? constraintName, DataColumn parentColumn, DataColumn childColumn) { DataColumn[] parentColumns = new DataColumn[] { parentColumn }; DataColumn[] childColumns = new DataColumn[] { childColumn }; @@ -63,14 +63,14 @@ namespace System.Data /// Initializes a new instance of the class with the specified name, /// and arrays of parent and child objects. /// - public ForeignKeyConstraint(string constraintName, DataColumn[] parentColumns, DataColumn[] childColumns) + public ForeignKeyConstraint(string? constraintName, DataColumn[] parentColumns, DataColumn[] childColumns) { Create(constraintName, parentColumns, childColumns); } // construct design time object [Browsable(false)] - public ForeignKeyConstraint(string constraintName, string parentTableName, string[] parentColumnNames, string[] childColumnNames, + public ForeignKeyConstraint(string? constraintName, string? parentTableName, string[] parentColumnNames, string[] childColumnNames, AcceptRejectRule acceptRejectRule, Rule deleteRule, Rule updateRule) { _constraintName = constraintName; @@ -84,7 +84,7 @@ namespace System.Data // construct design time object [Browsable(false)] - public ForeignKeyConstraint(string constraintName, string parentTableName, string parentTableNamespace, string[] parentColumnNames, + public ForeignKeyConstraint(string? constraintName, string? parentTableName, string? parentTableNamespace, string[] parentColumnNames, string[] childColumnNames, AcceptRejectRule acceptRejectRule, Rule deleteRule, Rule updateRule) { _constraintName = constraintName; @@ -126,7 +126,7 @@ namespace System.Data /// Gets the child table of this constraint. /// [ReadOnly(true)] - public override DataTable Table + public override DataTable? Table { get { @@ -196,7 +196,7 @@ namespace System.Data internal override bool CanEnableConstraint() { - if (Table.DataSet == null || !Table.DataSet.EnforceConstraints) + if (Table!.DataSet == null || !Table.DataSet.EnforceConstraints) { return true; } @@ -254,6 +254,8 @@ namespace System.Data internal void CascadeDelete(DataRow row) { + Debug.Assert(row.Table.DataSet != null); + if (-1 == row._newRecord) { return; @@ -352,6 +354,8 @@ namespace System.Data internal void CascadeRollback(DataRow row) { + Debug.Assert(row.Table.DataSet != null); + Index childIndex = _childKey.GetSortIndex(row.RowState == DataRowState.Deleted ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows); object[] key = row.GetKeyValues(_parentKey, row.RowState == DataRowState.Modified ? DataRowVersion.Current : DataRowVersion.Default); @@ -395,6 +399,8 @@ namespace System.Data internal void CascadeUpdate(DataRow row) { + Debug.Assert(Table?.DataSet != null && row.Table.DataSet != null); + if (-1 == row._newRecord) { return; @@ -486,6 +492,7 @@ namespace System.Data internal void CheckCanClearParentTable(DataTable table) { + Debug.Assert(Table?.DataSet != null); if (Table.DataSet.EnforceConstraints && Table.Rows.Count > 0) { throw ExceptionBuilder.FailedClearParentTable(table.TableName, ConstraintName, Table.TableName); @@ -494,7 +501,7 @@ namespace System.Data internal void CheckCanRemoveParentRow(DataRow row) { - Debug.Assert(Table.DataSet != null, "Relation " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); + Debug.Assert(Table?.DataSet != null, "Relation " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); if (!Table.DataSet.EnforceConstraints) { return; @@ -507,7 +514,7 @@ namespace System.Data internal void CheckCascade(DataRow row, DataRowAction action) { - Debug.Assert(Table.DataSet != null, "ForeignKeyConstraint " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); + Debug.Assert(Table?.DataSet != null, "ForeignKeyConstraint " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); if (row._inCascade) { @@ -555,7 +562,7 @@ namespace System.Data if ((action == DataRowAction.Change || action == DataRowAction.Add || action == DataRowAction.Rollback) && - Table.DataSet != null && Table.DataSet.EnforceConstraints && + Table!.DataSet != null && Table.DataSet.EnforceConstraints && childRow.HasKeyChanged(_childKey)) { // This branch is for cascading case verification. @@ -565,7 +572,7 @@ namespace System.Data if (childRow.HasVersion(version)) { // this is the new proposed value for the parent. - DataRow parentRow = DataRelation.GetParentRow(ParentKey, ChildKey, childRow, version); + DataRow? parentRow = DataRelation.GetParentRow(ParentKey, ChildKey, childRow, version); if (parentRow != null && parentRow._inCascade) { object[] parentKeyValues = parentRow.GetKeyValues(_parentKey, action == DataRowAction.Rollback ? version : DataRowVersion.Default); @@ -593,7 +600,7 @@ namespace System.Data for (lo = 0; lo < childValues.Length; lo++) { DataColumn column = _parentKey.ColumnsReference[lo]; - object value = column.ConvertValue(childValues[lo]); + object? value = column.ConvertValue(childValues[lo]); if (0 != column.CompareValueTo(childRow._tempRecord, value)) { break; @@ -671,18 +678,18 @@ namespace System.Data internal override bool ContainsColumn(DataColumn column) => _parentKey.ContainsColumn(column) || _childKey.ContainsColumn(column); - internal override Constraint Clone(DataSet destination) => Clone(destination, false); + internal override Constraint? Clone(DataSet destination) => Clone(destination, false); - internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup) + internal override Constraint? Clone(DataSet destination, bool ignorNSforTableLookup) { int iDest; if (ignorNSforTableLookup) { - iDest = destination.Tables.IndexOf(Table.TableName); + iDest = destination.Tables.IndexOf(Table!.TableName); } else { - iDest = destination.Tables.IndexOf(Table.TableName, Table.Namespace, false); // pass false for last param + iDest = destination.Tables.IndexOf(Table!.TableName, Table.Namespace, false); // pass false for last param // to be backward compatable, otherwise meay cause new exception } @@ -744,7 +751,7 @@ namespace System.Data } - internal ForeignKeyConstraint Clone(DataTable destination) + internal ForeignKeyConstraint? Clone(DataTable destination) { Debug.Assert(Table == RelatedTable, "We call this clone just if we have the same datatable as parent and child "); int keys = Columns.Length; @@ -785,7 +792,7 @@ namespace System.Data return clone; } - private void Create(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns) + private void Create(string? relationName, DataColumn[] parentColumns, DataColumn[] childColumns) { if (parentColumns.Length == 0 || childColumns.Length == 0) { @@ -846,7 +853,7 @@ namespace System.Data /// /// Gets a value indicating whether the current is identical to the specified object. /// - public override bool Equals(object key) + public override bool Equals(object? key) { if (!(key is ForeignKeyConstraint)) { @@ -894,9 +901,9 @@ namespace System.Data } } - internal DataRelation FindParentRelation() + internal DataRelation? FindParentRelation() { - DataRelationCollection rels = Table.ParentRelations; + DataRelationCollection rels = Table!.ParentRelations; for (int i = 0; i < rels.Count; i++) { diff --git a/src/libraries/System.Data.Common/src/System/Data/IColumnMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/IColumnMappingCollection.cs index 1f001e1..5a3e6a1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IColumnMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IColumnMappingCollection.cs @@ -9,9 +9,9 @@ namespace System.Data { object this[string index] { get; set; } IColumnMapping Add(string sourceColumnName, string dataSetColumnName); - bool Contains(string sourceColumnName); + bool Contains(string? sourceColumnName); IColumnMapping GetByDataSetColumn(string dataSetColumnName); - int IndexOf(string sourceColumnName); + int IndexOf(string? sourceColumnName); void RemoveAt(string sourceColumnName); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/IDataParameter.cs b/src/libraries/System.Data.Common/src/System/Data/IDataParameter.cs index 5e53cc5..3cdcf67 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDataParameter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDataParameter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics.CodeAnalysis; namespace System.Data diff --git a/src/libraries/System.Data.Common/src/System/Data/IDataParameterCollection.cs b/src/libraries/System.Data.Common/src/System/Data/IDataParameterCollection.cs index 3e08db0..6ad6f58 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDataParameterCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDataParameterCollection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; namespace System.Data diff --git a/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs b/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs index ff658f0..86ffd48 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data { public interface IDataReader : IDisposable, IDataRecord diff --git a/src/libraries/System.Data.Common/src/System/Data/IDataRecord.cs b/src/libraries/System.Data.Common/src/System/Data/IDataRecord.cs index 5620e5f..2563e75 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDataRecord.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDataRecord.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data { public interface IDataRecord diff --git a/src/libraries/System.Data.Common/src/System/Data/IDbCommand.cs b/src/libraries/System.Data.Common/src/System/Data/IDbCommand.cs index 770b0a9..823f734 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDbCommand.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDbCommand.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics.CodeAnalysis; namespace System.Data diff --git a/src/libraries/System.Data.Common/src/System/Data/IDbConnection.cs b/src/libraries/System.Data.Common/src/System/Data/IDbConnection.cs index ef9e4f9..6ad10de 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDbConnection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDbConnection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics.CodeAnalysis; namespace System.Data diff --git a/src/libraries/System.Data.Common/src/System/Data/IDbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/IDbDataAdapter.cs index 1d6deb1..f42492c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDbDataAdapter.cs @@ -5,9 +5,9 @@ namespace System.Data { public interface IDbDataAdapter : IDataAdapter { - IDbCommand SelectCommand { get; set; } - IDbCommand InsertCommand { get; set; } - IDbCommand UpdateCommand { get; set; } - IDbCommand DeleteCommand { get; set; } + IDbCommand? SelectCommand { get; set; } + IDbCommand? InsertCommand { get; set; } + IDbCommand? UpdateCommand { get; set; } + IDbCommand? DeleteCommand { get; set; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/IDbDataParameter.cs b/src/libraries/System.Data.Common/src/System/Data/IDbDataParameter.cs index e8c435c..f312a1e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDbDataParameter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDbDataParameter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data { public interface IDbDataParameter : IDataParameter diff --git a/src/libraries/System.Data.Common/src/System/Data/IDbTransaction.cs b/src/libraries/System.Data.Common/src/System/Data/IDbTransaction.cs index 3241b04..8a9fc33 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDbTransaction.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDbTransaction.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data { public interface IDbTransaction : IDisposable diff --git a/src/libraries/System.Data.Common/src/System/Data/ITableMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ITableMappingCollection.cs index f8158ea..9a3893c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ITableMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ITableMappingCollection.cs @@ -9,9 +9,9 @@ namespace System.Data { object this[string index] { get; set; } ITableMapping Add(string sourceTableName, string dataSetTableName); - bool Contains(string sourceTableName); + bool Contains(string? sourceTableName); ITableMapping GetByDataSetTable(string dataSetTableName); - int IndexOf(string sourceTableName); + int IndexOf(string? sourceTableName); void RemoveAt(string sourceTableName); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs b/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs index 9953e1f..e80c87e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs @@ -19,12 +19,12 @@ namespace System.Data /// /// A Comparer that compares a Key and a Row. /// - internal Func comparerKeyRow; // comparer for DataView.Find(.. + internal Func? comparerKeyRow; // comparer for DataView.Find(.. /// /// Builds the sort expression in case multiple selector/comparers are added. /// - internal readonly SortExpressionBuilder sortExpressionBuilder; + internal readonly SortExpressionBuilder? sortExpressionBuilder; /// /// Constructs a LinkDataView and its parent DataView. @@ -32,7 +32,7 @@ namespace System.Data /// /// The input table from which LinkDataView is to be created. /// The sort expression builder in case multiple selectors/comparers are added. - internal LinqDataView(DataTable table, SortExpressionBuilder sortExpressionBuilder) + internal LinqDataView(DataTable table, SortExpressionBuilder? sortExpressionBuilder) : base(table) { Debug.Assert(table != null, "null DataTable"); @@ -53,10 +53,10 @@ namespace System.Data /// Combined sort expression build using mutiple sort expressions. internal LinqDataView( DataTable table, - Predicate predicate_system, - Comparison comparison, - Func comparerKeyRow, - SortExpressionBuilder sortExpressionBuilder) + Predicate? predicate_system, + Comparison? comparison, + Func? comparerKeyRow, + SortExpressionBuilder? sortExpressionBuilder) : base(table, predicate_system, comparison, @@ -69,7 +69,7 @@ namespace System.Data /// /// Gets or sets the expression used to filter which rows are viewed in the LinqDataView /// - public override string RowFilter + public override string? RowFilter { get { @@ -122,11 +122,11 @@ namespace System.Data } else // find for expression based sort { - if (sortExpressionBuilder.Count != 1) + if (sortExpressionBuilder!.Count != 1) throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); Index.ComparisonBySelector compareDelg = - new Index.ComparisonBySelector(comparerKeyRow); + new Index.ComparisonBySelector(comparerKeyRow!); List keyList = new List(); keyList.Add(key); @@ -141,7 +141,7 @@ namespace System.Data /// them to Find using multiple keys. /// This overriden method prevents users calling multi-key find on dataview. /// - internal override int FindByKey(object[] key) + internal override int FindByKey(object?[] key) { // must have string or expression based sort specified if (base.SortComparison == null && string.IsNullOrEmpty(base.Sort)) @@ -149,7 +149,7 @@ namespace System.Data // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } - else if (base.SortComparison != null && key.Length != sortExpressionBuilder.Count) + else if (base.SortComparison != null && key.Length != sortExpressionBuilder!.Count) { throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); } @@ -162,10 +162,10 @@ namespace System.Data else { Index.ComparisonBySelector compareDelg = - new Index.ComparisonBySelector(comparerKeyRow); + new Index.ComparisonBySelector(comparerKeyRow!); - List keyList = new List(); - foreach (object singleKey in key) + List keyList = new List(); + foreach (object? singleKey in key) { keyList.Add(singleKey); } @@ -181,7 +181,7 @@ namespace System.Data /// Since LinkDataView does not support multiple selectors/comparers, it does not make sense for /// them to Find using multiple keys. This overriden method prevents users calling multi-key find on dataview. /// - internal override DataRowView[] FindRowsByKey(object[] key) + internal override DataRowView[] FindRowsByKey(object?[] key) { // must have string or expression based sort specified if (base.SortComparison == null && string.IsNullOrEmpty(base.Sort)) @@ -189,7 +189,7 @@ namespace System.Data // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } - else if (base.SortComparison != null && key.Length != sortExpressionBuilder.Count) + else if (base.SortComparison != null && key.Length != sortExpressionBuilder!.Count) { throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); } @@ -201,8 +201,8 @@ namespace System.Data else { Range range = FindRecords( - new Index.ComparisonBySelector(comparerKeyRow), - new List(key)); + new Index.ComparisonBySelector(comparerKeyRow!), + new List(key)); return base.GetDataRowViewFromRange(range); } } @@ -214,7 +214,7 @@ namespace System.Data /// Overriding DataView's SetIndex to prevent users from setting RowState filter to anything other /// than CurrentRows. /// - internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter newRowFilter) + internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter? newRowFilter) { // Throw only if expressions (filter or sort) are used and rowstate is not current rows if ((base.SortComparison != null || base.RowPredicate != null) && newRowStates != DataViewRowState.CurrentRows) @@ -230,7 +230,8 @@ namespace System.Data #endregion #region IBindingList - +// TODO: Enable after System.ComponentModel.TypeConverter is annotated +#nullable disable /// /// Clears both expression-based and DataView's string-based sorting. /// @@ -281,7 +282,7 @@ namespace System.Data return !(base.SortComparison == null && base.Sort.Length == 0); } } - +#nullable enable #endregion } } diff --git a/src/libraries/System.Data.Common/src/System/Data/MergeFailedEvent.cs b/src/libraries/System.Data.Common/src/System/Data/MergeFailedEvent.cs index 17d7132..3a87c42 100644 --- a/src/libraries/System.Data.Common/src/System/Data/MergeFailedEvent.cs +++ b/src/libraries/System.Data.Common/src/System/Data/MergeFailedEvent.cs @@ -5,7 +5,7 @@ namespace System.Data { public class MergeFailedEventArgs : EventArgs { - public MergeFailedEventArgs(DataTable table, string conflict) + public MergeFailedEventArgs(DataTable? table, string conflict) { Table = table; Conflict = conflict; @@ -14,7 +14,7 @@ namespace System.Data /// /// Gets the name of the . /// - public DataTable Table { get; } + public DataTable? Table { get; } /// /// Gets a description of the merge conflict. diff --git a/src/libraries/System.Data.Common/src/System/Data/Merger.cs b/src/libraries/System.Data.Common/src/System/Data/Merger.cs index c5ee3b8..a06f531 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -9,8 +9,8 @@ namespace System.Data { internal sealed class Merger { - private readonly DataSet _dataSet; - private readonly DataTable _dataTable; + private readonly DataSet? _dataSet; + private readonly DataTable? _dataTable; private readonly bool _preserveChanges; private readonly MissingSchemaAction _missingSchemaAction; private readonly bool _isStandAlonetable; @@ -41,13 +41,15 @@ namespace System.Data internal void MergeDataSet(DataSet source) { + Debug.Assert(_dataSet != null); + if (source == _dataSet) return; //somebody is doing an 'automerge' bool fEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; _IgnoreNSforTableLookup = (_dataSet._namespaceURI != source._namespaceURI); // if two DataSets have different // Namespaces, ignore NS for table lookups as we won't be able to find the right tables which inherits its NS - List existingColumns = null; // need to cache existing columns + List? existingColumns = null; // need to cache existing columns if (MissingSchemaAction.Add == _missingSchemaAction) { @@ -61,7 +63,6 @@ namespace System.Data } } - for (int i = 0; i < source.Tables.Count; i++) { MergeTableData(source.Tables[i]); // since column expression might have dependency on relation, we do not set @@ -88,11 +89,11 @@ namespace System.Data DataTable targetTable; if (_IgnoreNSforTableLookup) { - targetTable = _dataSet.Tables[sourceTable.TableName]; + targetTable = _dataSet.Tables[sourceTable.TableName]!; } else { - targetTable = _dataSet.Tables[sourceTable.TableName, sourceTable.Namespace]; // we know that target table won't be null since MissingSchemaAction is Add , we have already added it! + targetTable = _dataSet.Tables[sourceTable.TableName, sourceTable.Namespace]!; // we know that target table won't be null since MissingSchemaAction is Add , we have already added it! } foreach (DataColumn dc in sourceTable.Columns) @@ -100,8 +101,8 @@ namespace System.Data // Should we overwrite the previous expression column? No, refer to spec, if it is new column we need to add the schema if (dc.Computed) { - DataColumn targetColumn = targetTable.Columns[dc.ColumnName]; - if (!existingColumns.Contains(targetColumn)) + DataColumn targetColumn = targetTable.Columns[dc.ColumnName]!; + if (!existingColumns!.Contains(targetColumn)) { targetColumn.Expression = dc.Expression; } @@ -124,13 +125,13 @@ namespace System.Data if (!_isStandAlonetable) { if (src.DataSet == _dataSet) return; //somebody is doing an 'automerge' - fEnforce = _dataSet.EnforceConstraints; + fEnforce = _dataSet!.EnforceConstraints; _dataSet.EnforceConstraints = false; } else { if (src == _dataTable) return; //somebody is doing an 'automerge' - _dataTable.SuspendEnforceConstraints = true; + _dataTable!.SuspendEnforceConstraints = true; } if (_dataSet != null) @@ -145,7 +146,7 @@ namespace System.Data else { // this is dt.Merge - if (_dataTable.DataSet == null || src.DataSet == null || src.DataSet._namespaceURI != _dataTable.DataSet._namespaceURI) + if (_dataTable!.DataSet == null || src.DataSet == null || src.DataSet._namespaceURI != _dataTable.DataSet._namespaceURI) { _IgnoreNSforTableLookup = true; } @@ -153,7 +154,7 @@ namespace System.Data MergeTableData(src); - DataTable dt = _dataTable; + DataTable? dt = _dataTable; if (dt == null && _dataSet != null) { dt = _IgnoreNSforTableLookup ? @@ -168,11 +169,11 @@ namespace System.Data if (!_isStandAlonetable) { - _dataSet.EnforceConstraints = fEnforce; + _dataSet!.EnforceConstraints = fEnforce; } else { - _dataTable.SuspendEnforceConstraints = false; + _dataTable!.SuspendEnforceConstraints = false; try { if (_dataTable.EnforceConstraints) @@ -197,7 +198,7 @@ namespace System.Data bool wasEmpty = dst.Rows.Count == 0; if (0 < rowsCount) { - Index ndxSearch = null; + Index? ndxSearch = null; DataKey key = default(DataKey); dst.SuspendIndexEvents(); try @@ -214,7 +215,7 @@ namespace System.Data // this improves performance by iterating over the rows instead of computing their position foreach (DataRow sourceRow in src.Rows) { - DataRow targetRow = null; + DataRow? targetRow = null; if (ndxSearch != null) { targetRow = dst.FindMergeTarget(sourceRow, key, ndxSearch); @@ -232,10 +233,12 @@ namespace System.Data internal void MergeRows(DataRow[] rows) { - DataTable src = null; - DataTable dst = null; + Debug.Assert(_dataSet != null); + + DataTable? src = null; + DataTable? dst = null; DataKey key = default(DataKey); - Index ndxSearch = null; + Index? ndxSearch = null; bool fEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; @@ -283,7 +286,7 @@ namespace System.Data ndxSearch.RemoveRef(); ndxSearch = null; } - ndxSearch = new Index(dst, dst._primaryKey.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null); + ndxSearch = new Index(dst, dst._primaryKey!.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null); ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected ndxSearch.AddRef(); // in past first adref was done in const } @@ -294,8 +297,8 @@ namespace System.Data continue; } - DataRow targetRow = null; - if (0 < dst.Rows.Count && ndxSearch != null) + DataRow? targetRow = null; + if (0 < dst!.Rows.Count && ndxSearch != null) { targetRow = dst.FindMergeTarget(row, key, ndxSearch); } @@ -316,12 +319,12 @@ namespace System.Data _dataSet.EnforceConstraints = fEnforce; } - private DataTable MergeSchema(DataTable table) + private DataTable? MergeSchema(DataTable table) { - DataTable targetTable = null; + DataTable? targetTable = null; if (!_isStandAlonetable) { - if (_dataSet.Tables.Contains(table.TableName, true)) + if (_dataSet!.Tables.Contains(table.TableName, true)) { if (_IgnoreNSforTableLookup) { @@ -346,7 +349,7 @@ namespace System.Data targetTable = table.Clone(table.DataSet); // if we are here mainly we are called from DataSet.Merge at this point we don't set //expression columns, since it might have refer to other columns via relation, so it won't find the table and we get exception; // do it after adding relations. - _dataSet.Tables.Add(targetTable); + _dataSet!.Tables.Add(targetTable); } else if (MissingSchemaAction.Error == _missingSchemaAction) { @@ -362,7 +365,7 @@ namespace System.Data for (int i = 0; i < table.Columns.Count; i++) { DataColumn src = table.Columns[i]; - DataColumn dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null; + DataColumn? dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null; if (dest == null) { if (MissingSchemaAction.Add == _missingSchemaAction) @@ -374,7 +377,7 @@ namespace System.Data { if (!_isStandAlonetable) { - _dataSet.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), _missingSchemaAction); + _dataSet!.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), _missingSchemaAction); } else { @@ -388,7 +391,7 @@ namespace System.Data ((dest.DataType == typeof(DateTime)) && (dest.DateTimeMode != src.DateTimeMode) && ((dest.DateTimeMode & src.DateTimeMode) != DataSetDateTime.Unspecified))) { if (!_isStandAlonetable) - _dataSet.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error); + _dataSet!.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error); else throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName)); } @@ -402,7 +405,7 @@ namespace System.Data { for (int i = oldCount; i < targetTable.Columns.Count; i++) { - targetTable.Columns[i].Expression = table.Columns[targetTable.Columns[i].ColumnName].Expression; + targetTable.Columns[i].Expression = table.Columns[targetTable.Columns[i].ColumnName]!.Expression; } } @@ -418,13 +421,13 @@ namespace System.Data DataColumn[] key = new DataColumn[tablePKey.Length]; for (int i = 0; i < tablePKey.Length; i++) { - key[i] = targetTable.Columns[tablePKey[i].ColumnName]; + key[i] = targetTable.Columns[tablePKey[i].ColumnName]!; } targetTable.PrimaryKey = key; } else if (tablePKey.Length != 0) { - _dataSet.RaiseMergeFailed(targetTable, SR.DataMerge_PrimaryKeyMismatch, _missingSchemaAction); + _dataSet!.RaiseMergeFailed(targetTable, SR.DataMerge_PrimaryKeyMismatch, _missingSchemaAction); } } else @@ -433,7 +436,7 @@ namespace System.Data { if (string.Compare(targetPKey[i].ColumnName, tablePKey[i].ColumnName, false, targetTable.Locale) != 0) { - _dataSet.RaiseMergeFailed(table, + _dataSet!.RaiseMergeFailed(table, SR.Format(SR.DataMerge_PrimaryKeyColumnsMismatch, targetPKey[i].ColumnName, tablePKey[i].ColumnName), _missingSchemaAction); } @@ -449,7 +452,7 @@ namespace System.Data private void MergeTableData(DataTable src) { - DataTable dest = MergeSchema(src); + DataTable? dest = MergeSchema(src); if (dest == null) return; dest.MergingData = true; @@ -473,11 +476,13 @@ namespace System.Data private void MergeConstraints(DataTable table) { + Debug.Assert(_dataSet != null); + // Merge constraints for (int i = 0; i < table.Constraints.Count; i++) { Constraint src = table.Constraints[i]; - Constraint dest = src.Clone(_dataSet, _IgnoreNSforTableLookup); + Constraint? dest = src.Clone(_dataSet, _IgnoreNSforTableLookup); if (dest == null) { @@ -488,7 +493,7 @@ namespace System.Data } else { - Constraint cons = dest.Table.Constraints.FindConstraint(dest); + Constraint? cons = dest.Table!.Constraints.FindConstraint(dest); if (cons == null) { if (MissingSchemaAction.Add == _missingSchemaAction) @@ -523,10 +528,11 @@ namespace System.Data private void MergeRelation(DataRelation relation) { + Debug.Assert(_dataSet != null); Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction || MissingSchemaAction.Add == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); - DataRelation destRelation = null; + DataRelation? destRelation = null; // try to find given relation in this dataSet @@ -548,7 +554,7 @@ namespace System.Data DataColumn dest = destRelation.ParentKey.ColumnsReference[i]; DataColumn src = relation.ParentKey.ColumnsReference[i]; - if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) + if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table!.Locale)) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), @@ -558,7 +564,7 @@ namespace System.Data dest = destRelation.ChildKey.ColumnsReference[i]; src = relation.ChildKey.ColumnsReference[i]; - if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) + if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table!.Locale)) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), @@ -572,19 +578,19 @@ namespace System.Data { // create identical realtion in the current dataset DataTable parent = _IgnoreNSforTableLookup ? - _dataSet.Tables[relation.ParentTable.TableName] : - _dataSet.Tables[relation.ParentTable.TableName, relation.ParentTable.Namespace]; + _dataSet.Tables[relation.ParentTable.TableName]! : + _dataSet.Tables[relation.ParentTable.TableName, relation.ParentTable.Namespace]!; DataTable child = _IgnoreNSforTableLookup ? - _dataSet.Tables[relation.ChildTable.TableName] : - _dataSet.Tables[relation.ChildTable.TableName, relation.ChildTable.Namespace]; + _dataSet.Tables[relation.ChildTable.TableName]! : + _dataSet.Tables[relation.ChildTable.TableName, relation.ChildTable.Namespace]!; DataColumn[] parentColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length]; DataColumn[] childColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length]; for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) { - parentColumns[i] = parent.Columns[relation.ParentKey.ColumnsReference[i].ColumnName]; - childColumns[i] = child.Columns[relation.ChildKey.ColumnsReference[i].ColumnName]; + parentColumns[i] = parent.Columns[relation.ParentKey.ColumnsReference[i].ColumnName]!; + childColumns[i] = child.Columns[relation.ChildKey.ColumnsReference[i].ColumnName]!; } try { @@ -596,6 +602,7 @@ namespace System.Data { ExceptionBuilder.TraceExceptionForCapture(e); _dataSet.RaiseMergeFailed(null, e.Message, _missingSchemaAction); + // TODO: destRelation may be null, causing an NRE below } } else @@ -605,9 +612,8 @@ namespace System.Data } } - MergeExtendedProperties(relation.ExtendedProperties, destRelation.ExtendedProperties); - - return; + // TODO: destRelation may be null, see comment above + MergeExtendedProperties(relation.ExtendedProperties, destRelation!.ExtendedProperties); } private void MergeExtendedProperties(PropertyCollection src, PropertyCollection dst) @@ -641,7 +647,7 @@ namespace System.Data DataColumn[] srcColumns = new DataColumn[dstColumns.Length]; for (int j = 0; j < dstColumns.Length; j++) { - srcColumns[j] = src.Columns[dstColumns[j].ColumnName]; + srcColumns[j] = src.Columns[dstColumns[j].ColumnName]!; } key = new DataKey(srcColumns, false); // DataKey will take ownership of srcColumns diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs index 6185686..cb010fc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs @@ -15,7 +15,7 @@ namespace System.Data.ProviderBase { if (returnProviderSpecificTypes) { - DbDataReader providerSpecificDataReader = (dataReader as DbDataReader); + DbDataReader? providerSpecificDataReader = (dataReader as DbDataReader); if (null != providerSpecificDataReader) { return new ProviderSpecificDataReader(dataReader, providerSpecificDataReader); diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs index 4422bf8..1fedea0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs @@ -31,33 +31,33 @@ namespace System.Data.ProviderBase // map xml string data to DataColumn with DataType=typeof(XmlDocument) private const int XmlDocument = 2; - private readonly DataSet _dataSet; // the current dataset, may be null if we are only filling a DataTable - private DataTable _dataTable; // the current DataTable, should never be null + private readonly DataSet? _dataSet; // the current dataset, may be null if we are only filling a DataTable + private DataTable? _dataTable; // the current DataTable, should never be null private readonly DataAdapter _adapter; private readonly DataReaderContainer _dataReader; - private readonly DataTable _schemaTable; // will be null if Fill without schema - private readonly DataTableMapping _tableMapping; + private readonly DataTable? _schemaTable; // will be null if Fill without schema + private readonly DataTableMapping? _tableMapping; // unique (generated) names based from DataReader.GetName(i) - private readonly string[] _fieldNames; + private readonly string[]? _fieldNames; - private readonly object[] _readerDataValues; - private object[] _mappedDataValues; // array passed to dataRow.AddUpdate(), if needed + private readonly object?[]? _readerDataValues; + private object?[]? _mappedDataValues; // array passed to dataRow.AddUpdate(), if needed - private int[] _indexMap; // index map that maps dataValues -> _mappedDataValues, if needed - private bool[] _chapterMap; // which DataReader indexes have chapters + private int[]? _indexMap; // index map that maps dataValues -> _mappedDataValues, if needed + private bool[]? _chapterMap; // which DataReader indexes have chapters - private int[] _xmlMap; // map which value in _readerDataValues to convert to a Xml datatype, (SqlXml/XmlDocument) + private int[]? _xmlMap; // map which value in _readerDataValues to convert to a Xml datatype, (SqlXml/XmlDocument) private int _mappedMode; // modes as described as above private int _mappedLength; private readonly LoadOption _loadOption; - internal SchemaMapping(DataAdapter adapter, DataSet dataset, DataTable datatable, DataReaderContainer dataReader, bool keyInfo, - SchemaType schemaType, string sourceTableName, bool gettingData, - DataColumn parentChapterColumn, object parentChapterValue) + internal SchemaMapping(DataAdapter adapter, DataSet? dataset, DataTable? datatable, DataReaderContainer dataReader, bool keyInfo, + SchemaType schemaType, string? sourceTableName, bool gettingData, + DataColumn? parentChapterColumn, object? parentChapterValue) { Debug.Assert(null != adapter, nameof(adapter)); Debug.Assert(null != dataReader, nameof(dataReader)); @@ -147,7 +147,7 @@ namespace System.Data.ProviderBase { if (null == _dataTable) { - _dataTable = _tableMapping.GetDataTableBySchemaAction(_dataSet, schemaAction); + _dataTable = _tableMapping.GetDataTableBySchemaAction(_dataSet!, schemaAction); } if (null != _dataTable) { @@ -174,7 +174,7 @@ namespace System.Data.ProviderBase } } - internal DataTable DataTable + internal DataTable? DataTable { get { @@ -182,7 +182,7 @@ namespace System.Data.ProviderBase } } - internal object[] DataValues + internal object?[]? DataValues { get { @@ -193,9 +193,9 @@ namespace System.Data.ProviderBase internal void ApplyToDataRow(DataRow dataRow) { DataColumnCollection columns = dataRow.Table.Columns; - _dataReader.GetValues(_readerDataValues); + _dataReader.GetValues(_readerDataValues!); - object[] mapped = GetMappedValues(); + object?[] mapped = GetMappedValues(); bool[] readOnly = new bool[mapped.Length]; for (int i = 0; i < readOnly.Length; ++i) { @@ -217,9 +217,9 @@ namespace System.Data.ProviderBase for (int i = 0; i < mapped.Length; ++i) { - if (null != mapped[i]) + if (mapped[i] is { } m) { - dataRow[i] = mapped[i]; + dataRow[i] = m; } } } @@ -251,11 +251,11 @@ namespace System.Data.ProviderBase for (int i = 0; i < length; i++) { - int k = _indexMap[i]; + int k = _indexMap![i]; if (0 <= k) { - _mappedDataValues[k] = _readerDataValues[i]; // from reader to dataset - if (_chapterMap[i]) + _mappedDataValues![k] = _readerDataValues![i]; // from reader to dataset + if (_chapterMap![i]) { _mappedDataValues[k] = null; // InvalidCast from DataReader to AutoIncrement DataColumn } @@ -269,8 +269,8 @@ namespace System.Data.ProviderBase for (int i = 0; i < length; i++) { - _mappedDataValues[i] = _readerDataValues[i]; // from reader to dataset - if (_chapterMap[i]) + _mappedDataValues![i] = _readerDataValues![i]; // from reader to dataset + if (_chapterMap![i]) { _mappedDataValues[i] = null; // InvalidCast from DataReader to AutoIncrement DataColumn } @@ -279,7 +279,7 @@ namespace System.Data.ProviderBase private void MappedIndex() { // mode 2 - Debug.Assert(_mappedLength == _indexMap.Length, "incorrect precomputed length"); + Debug.Assert(_mappedLength == _indexMap!.Length, "incorrect precomputed length"); int length = _mappedLength; for (int i = 0; i < length; i++) @@ -287,14 +287,14 @@ namespace System.Data.ProviderBase int k = _indexMap[i]; if (0 <= k) { - _mappedDataValues[k] = _readerDataValues[i]; // from reader to dataset + _mappedDataValues![k] = _readerDataValues![i]; // from reader to dataset } } } private void MappedValues() { // mode 1 - Debug.Assert(_mappedLength == Math.Min(_readerDataValues.Length, _mappedDataValues.Length), "incorrect precomputed length"); + Debug.Assert(_mappedLength == Math.Min(_readerDataValues!.Length, _mappedDataValues!.Length), "incorrect precomputed length"); int length = _mappedLength; for (int i = 0; i < length; ++i) @@ -303,8 +303,10 @@ namespace System.Data.ProviderBase }; } - private object[] GetMappedValues() + private object?[] GetMappedValues() { // mode 0 + Debug.Assert(_readerDataValues != null); + if (null != _xmlMap) { for (int i = 0; i < _xmlMap.Length; ++i) @@ -312,10 +314,9 @@ namespace System.Data.ProviderBase if (0 != _xmlMap[i]) { // get the string/SqlString xml value - string xml = _readerDataValues[i] as string; - if ((null == xml) && (_readerDataValues[i] is System.Data.SqlTypes.SqlString)) + string? xml = _readerDataValues[i] as string; + if ((null == xml) && (_readerDataValues[i] is System.Data.SqlTypes.SqlString x)) { - System.Data.SqlTypes.SqlString x = (System.Data.SqlTypes.SqlString)_readerDataValues[i]; if (!x.IsNull) { xml = x.Value; @@ -338,7 +339,7 @@ namespace System.Data.ProviderBase case SqlXml: // turn string into a SqlXml value for DataColumn System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings(); settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment; - System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(xml), settings, (string)null); + System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(xml), settings, (string?)null); _readerDataValues[i] = new System.Data.SqlTypes.SqlXml(reader); break; case XmlDocument: // turn string into XmlDocument value for DataColumn @@ -377,13 +378,13 @@ namespace System.Data.ProviderBase MappedChapterIndex(); break; } - return _mappedDataValues; + return _mappedDataValues!; } internal void LoadDataRowWithClear() { // for FillErrorEvent to ensure no values leftover from previous row - for (int i = 0; i < _readerDataValues.Length; ++i) + for (int i = 0; i < _readerDataValues!.Length; ++i) { _readerDataValues[i] = null; } @@ -394,8 +395,8 @@ namespace System.Data.ProviderBase { try { - _dataReader.GetValues(_readerDataValues); - object[] mapped = GetMappedValues(); + _dataReader.GetValues(_readerDataValues!); + object?[] mapped = GetMappedValues(); DataRow dataRow; switch (_loadOption) @@ -403,13 +404,13 @@ namespace System.Data.ProviderBase case LoadOption.OverwriteChanges: case LoadOption.PreserveChanges: case LoadOption.Upsert: - dataRow = _dataTable.LoadDataRow(mapped, _loadOption); + dataRow = _dataTable!.LoadDataRow(mapped, _loadOption); break; case (LoadOption)4: // true - dataRow = _dataTable.LoadDataRow(mapped, true); + dataRow = _dataTable!.LoadDataRow(mapped, true); break; case (LoadOption)5: // false - dataRow = _dataTable.LoadDataRow(mapped, false); + dataRow = _dataTable!.LoadDataRow(mapped, false); break; default: Debug.Fail("unexpected LoadOption"); @@ -431,11 +432,11 @@ namespace System.Data.ProviderBase private void FreeDataRowChapters() { - for (int i = 0; i < _chapterMap.Length; ++i) + for (int i = 0; i < _chapterMap!.Length; ++i) { if (_chapterMap[i]) { - IDisposable disposable = (_readerDataValues[i] as IDisposable); + IDisposable? disposable = (_readerDataValues![i] as IDisposable); if (null != disposable) { _readerDataValues[i] = null; @@ -449,12 +450,12 @@ namespace System.Data.ProviderBase { int datarowadded = 0; - int rowLength = _chapterMap.Length; + int rowLength = _chapterMap!.Length; for (int i = 0; i < rowLength; ++i) { if (_chapterMap[i]) { - object readerValue = _readerDataValues[i]; + object? readerValue = _readerDataValues![i]; if ((null != readerValue) && !Convert.IsDBNull(readerValue)) { _readerDataValues[i] = null; @@ -469,17 +470,17 @@ namespace System.Data.ProviderBase DataColumn parentChapterColumn; if (null == _indexMap) { - parentChapterColumn = _dataTable.Columns[i]; + parentChapterColumn = _dataTable!.Columns[i]; parentChapterValue = dataRow[parentChapterColumn]; } else { - parentChapterColumn = _dataTable.Columns[_indexMap[i]]; + parentChapterColumn = _dataTable!.Columns[_indexMap[i]]; parentChapterValue = dataRow[parentChapterColumn]; } // correct on Fill, not FillFromReader - string chapterTableName = _tableMapping.SourceTable + _fieldNames[i]; + string chapterTableName = _tableMapping!.SourceTable + _fieldNames![i]; DataReaderContainer readerHandler = DataReaderContainer.Create(nestedReader, _dataReader.ReturnProviderSpecificTypes); datarowadded += _adapter.FillFromReader(_dataSet, null, chapterTableName, readerHandler, 0, 0, parentChapterColumn, parentChapterValue); @@ -521,7 +522,7 @@ namespace System.Data.ProviderBase return tmp; } - private void AddItemToAllowRollback(ref List items, object value) + private void AddItemToAllowRollback(ref List? items, object value) { if (null == items) { @@ -530,7 +531,7 @@ namespace System.Data.ProviderBase items.Add(value); } - private void RollbackAddedItems(List items) + private void RollbackAddedItems(List? items) { if (null != items) { @@ -539,7 +540,7 @@ namespace System.Data.ProviderBase // remove columns that were added now that we are failing if (null != items[i]) { - DataColumn column = (items[i] as DataColumn); + DataColumn? column = (items[i] as DataColumn); if (null != column) { if (null != column.Table) @@ -549,7 +550,7 @@ namespace System.Data.ProviderBase } else { - DataTable table = (items[i] as DataTable); + DataTable? table = (items[i] as DataTable); if (null != table) { if (null != table.DataSet) @@ -563,16 +564,20 @@ namespace System.Data.ProviderBase } } - private object[] SetupSchemaWithoutKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn parentChapterColumn, object chapterValue) + private object[]? SetupSchemaWithoutKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn? parentChapterColumn, object? chapterValue) { - int[] columnIndexMap = null; - bool[] chapterIndexMap = null; + Debug.Assert(_dataTable != null); + Debug.Assert(_fieldNames != null); + Debug.Assert(_tableMapping != null); + + int[]? columnIndexMap = null; + bool[]? chapterIndexMap = null; int mappingCount = 0; int count = _dataReader.FieldCount; - object[] dataValues = null; - List addedItems = null; + object[]? dataValues = null; + List? addedItems = null; try { DataColumnCollection columnCollection = _dataTable.Columns; @@ -618,7 +623,7 @@ namespace System.Data.ProviderBase _xmlMap[i] = XmlDocument; // track its xml data } - DataColumn dataColumn; + DataColumn? dataColumn; if (alwaysCreateColumns) { dataColumn = DataColumnMapping.CreateDataColumnBySchemaAction(_fieldNames[i], _fieldNames[i], _dataTable, fieldType, schemaAction); @@ -694,7 +699,7 @@ namespace System.Data.ProviderBase mappingCount++; } bool addDataRelation = false; - DataColumn chapterColumn = null; + DataColumn? chapterColumn = null; if (null != chapterValue) { // add the extra column in the child table Type fieldType = chapterValue.GetType(); @@ -743,7 +748,7 @@ namespace System.Data.ProviderBase if (addDataRelation) { - AddRelation(parentChapterColumn, chapterColumn); + AddRelation(parentChapterColumn!, chapterColumn!); } } catch (Exception e) when (ADP.IsCatchableOrSecurityExceptionType(e)) @@ -754,8 +759,13 @@ namespace System.Data.ProviderBase return dataValues; } - private object[] SetupSchemaWithKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn parentChapterColumn, object chapterValue) + private object[]? SetupSchemaWithKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, bool gettingData, DataColumn? parentChapterColumn, object? chapterValue) { + Debug.Assert(_dataTable != null); + Debug.Assert(_schemaTable != null); + Debug.Assert(_fieldNames != null); + Debug.Assert(_tableMapping != null); + // must sort rows from schema table by ordinal because Jet is sorted by coumn name DbSchemaRow[] schemaRows = DbSchemaRow.GetSortedSchemaRows(_schemaTable, _dataReader.ReturnProviderSpecificTypes); Debug.Assert(null != schemaRows, "SchemaSetup - null DbSchemaRow[]"); @@ -772,23 +782,23 @@ namespace System.Data.ProviderBase bool addPrimaryKeys = (((0 == _dataTable.PrimaryKey.Length) && ((4 <= (int)_loadOption) || (0 == _dataTable.Rows.Count))) || (0 == _dataTable.Columns.Count)); - DataColumn[] keys = null; + DataColumn[]? keys = null; int keyCount = 0; bool isPrimary = true; // assume key info (if any) is about a primary key - string keyBaseTable = null; - string commonBaseTable = null; + string? keyBaseTable = null; + string? commonBaseTable = null; bool keyFromMultiTable = false; bool commonFromMultiTable = false; - int[] columnIndexMap = null; - bool[] chapterIndexMap = null; + int[]? columnIndexMap = null; + bool[]? chapterIndexMap = null; int mappingCount = 0; - object[] dataValues = null; - List addedItems = null; + object[]? dataValues = null; + List? addedItems = null; DataColumnCollection columnCollection = _dataTable.Columns; try { @@ -799,7 +809,7 @@ namespace System.Data.ProviderBase int unsortedIndex = schemaRow.UnsortedIndex; bool ischapter = false; - Type fieldType = schemaRow.DataType; + Type? fieldType = schemaRow.DataType; if (null == fieldType) { fieldType = _dataReader.GetFieldType(sortedIndex); @@ -837,7 +847,7 @@ namespace System.Data.ProviderBase _xmlMap[sortedIndex] = XmlDocument; } - DataColumn dataColumn = null; + DataColumn? dataColumn = null; if (!schemaRow.IsHidden) { dataColumn = _tableMapping.GetDataColumn(_fieldNames[sortedIndex], fieldType, _dataTable, mappingAction, schemaAction); @@ -1037,7 +1047,7 @@ namespace System.Data.ProviderBase } bool addDataRelation = false; - DataColumn chapterColumn = null; + DataColumn? chapterColumn = null; if (null != chapterValue) { // add the extra column in the child table Type fieldType = chapterValue.GetType(); @@ -1078,7 +1088,7 @@ namespace System.Data.ProviderBase } else { - UniqueConstraint unique = new UniqueConstraint("", keys); + UniqueConstraint? unique = new UniqueConstraint("", keys); ConstraintCollection constraints = _dataTable.Constraints; int constraintCount = constraints.Count; for (int i = 0; i < constraintCount; ++i) @@ -1117,7 +1127,7 @@ namespace System.Data.ProviderBase } if (addDataRelation) { - AddRelation(parentChapterColumn, chapterColumn); + AddRelation(parentChapterColumn!, chapterColumn!); } } catch (Exception e) when (ADP.IsCatchableOrSecurityExceptionType(e)) @@ -1131,7 +1141,7 @@ namespace System.Data.ProviderBase private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) { DataColumnCollection columns = schemaRow.Table.Columns; - DataColumn column; + DataColumn? column; column = columns[SchemaTableOptionalColumn.DefaultValue]; if (null != column) @@ -1211,7 +1221,7 @@ namespace System.Data.ProviderBase } } - private object[] SetupMapping(int count, DataColumnCollection columnCollection, DataColumn chapterColumn, object chapterValue) + private object[] SetupMapping(int count, DataColumnCollection columnCollection, DataColumn? chapterColumn, object? chapterValue) { object[] dataValues = new object[count]; @@ -1246,7 +1256,7 @@ namespace System.Data.ProviderBase } if (null != chapterColumn) { // value from parent tracked into child table - _mappedDataValues[chapterColumn.Ordinal] = chapterValue; + _mappedDataValues![chapterColumn.Ordinal] = chapterValue; } return dataValues; } diff --git a/src/libraries/System.Data.Common/src/System/Data/RbTree.cs b/src/libraries/System.Data.Common/src/System/Data/RbTree.cs index 84c30e2..4c40476 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RbTree.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RbTree.cs @@ -10,6 +10,7 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -95,8 +96,8 @@ namespace System.Data internal const int DefaultPageSize = 32; /* 512 = 2^9 32 million nodes*/ internal const int NIL = 0; // 0th page, 0th slot for each tree till CLR static & generics issue is fixed - private TreePage[] _pageTable; // initial size 4, then doubles (grows) - it never shrinks - private int[] _pageTableMap; + private TreePage?[] _pageTable = default!; // initial size 4, then doubles (grows) - it never shrinks. Late-initialized to non-null in InitTree. + private int[] _pageTableMap = default!; // Late-initialized to non-null in InitTree private int _inUsePageCount; // contains count of allocated pages per tree, its <= the capacity of pageTable private int _nextFreePageLine; // used for keeping track of position of last used free page in pageTable public int root; @@ -106,8 +107,8 @@ namespace System.Data private int _inUseSatelliteTreeCount; // total number of satellite associated with this tree. private readonly TreeAccessMethod _accessMethod; - protected abstract int CompareNode(K record1, K record2); - protected abstract int CompareSateliteTreeNode(K record1, K record2); + protected abstract int CompareNode([AllowNull] K record1, [AllowNull] K record2); + protected abstract int CompareSateliteTreeNode([AllowNull] K record1, [AllowNull] K record2); protected RBTree(TreeAccessMethod accessMethod) { @@ -125,9 +126,9 @@ namespace System.Data AllocPage(DefaultPageSize); // alloc storage for reserved NIL node. segment 0, slot 0; Initialize NIL - _pageTable[0]._slots[0]._nodeColor = NodeColor.black; - _pageTable[0]._slotMap[0] = 0x1; - _pageTable[0].InUseCount = 1; + _pageTable[0]!._slots[0]._nodeColor = NodeColor.black; + _pageTable[0]!._slotMap[0] = 0x1; + _pageTable[0]!.InUseCount = 1; _inUseNodeCount = 1; _inUseSatelliteTreeCount = 0; // total number of satellite associated with this tree. @@ -170,9 +171,9 @@ namespace System.Data _pageTableMap = newPageTableMap; _pageTable[freePageIndex] = new TreePage(size); } - _pageTable[freePageIndex].PageId = freePageIndex; + _pageTable[freePageIndex]!.PageId = freePageIndex; _inUsePageCount++; - return _pageTable[freePageIndex]; + return _pageTable[freePageIndex]!; } /* MarkPageFull() @@ -245,7 +246,7 @@ namespace System.Data */ private void FreeNode(int nodeId) { - TreePage page = _pageTable[nodeId >> 16]; + TreePage page = _pageTable[nodeId >> 16]!; int slotIndex = nodeId & 0xFFFF; page._slots[slotIndex] = default(Node); @@ -336,10 +337,10 @@ namespace System.Data * Use bitmap associated with page to allocate a slot. * mark the slot as used and return its index. */ - private int GetNewNode(K key) + private int GetNewNode([AllowNull] K key) { // find page with free slots, if none, allocate a new page - TreePage page = null; + TreePage? page = null; int freePageIndex = GetIndexOfPageWithFreeSlot(true); if (freePageIndex != -1) @@ -358,7 +359,7 @@ namespace System.Data page = AllocPage(64 * 1024); // Page size to accomodate more than 16 million slots (Max 2 Billion and 16 million slots) // page contains atleast 1 free slot. - int slotId = page.AllocSlot(this); + int slotId = page!.AllocSlot(this); if (slotId == -1) throw ExceptionBuilder.InternalRBTreeError(RBTreeError.NoFreeSlots); @@ -1204,7 +1205,7 @@ namespace System.Data return root_id; } - private int SearchSubTree(int root_id, K key) + private int SearchSubTree(int root_id, [AllowNull] K key) { if (root_id != NIL && _accessMethod != TreeAccessMethod.KEY_SEARCH_AND_INDEX) { @@ -1293,7 +1294,7 @@ namespace System.Data { return new NodePath(SearchSubTree(Next(nodeId), key), nodeId); } - else if (!Key(nodeId).Equals(key)) + else if (!Key(nodeId)!.Equals(key)) { nodeId = NIL; } @@ -1555,7 +1556,7 @@ namespace System.Data // Begin: List of methods for making it easy to work with ArrayList - public int Add(K item) //Insert (int record) + public int Add([AllowNull] K item) //Insert (int record) { int nodeId = GetNewNode(item); RBInsert(NIL, nodeId, NIL, -1, false); @@ -1577,7 +1578,7 @@ namespace System.Data // BIG ASSUMPTION: There is not satellite tree, this is INDEX_ONLY. if (nodeId != NIL) { - if ((object)Key(nodeId) == (object)item) + if ((object)Key(nodeId)! == (object)item!) { return GetIndexByNode(nodeId); } @@ -1662,7 +1663,8 @@ namespace System.Data int x_id = Minimum(root); for (int i = 0; i < count; ++i) { - array[index + i] = Key(x_id); + // Can't annotate generic array for element nullability + array[index + i] = Key(x_id)!; x_id = Successor(x_id); } } @@ -1676,7 +1678,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].rightId = rightNodeId; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._rightId = rightNodeId; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._rightId = rightNodeId; } private void SetLeft(int nodeId, int leftNodeId) @@ -1686,7 +1688,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].leftId = leftNodeId; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._leftId = leftNodeId; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._leftId = leftNodeId; } private void SetParent(int nodeId, int parentNodeId) @@ -1697,7 +1699,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].parentId = parentNodeId; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._parentId = parentNodeId; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._parentId = parentNodeId; } private void SetColor(int nodeId, NodeColor color) @@ -1708,7 +1710,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].nodeColor = color; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._nodeColor = color; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._nodeColor = color; } private void SetKey(int nodeId, K key) @@ -1718,7 +1720,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].keyOfNode = key; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._keyOfNode = key; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._keyOfNode = key; } private void SetNext(int nodeId, int nextNodeId) @@ -1728,17 +1730,17 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].nextId = nextNodeId; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._nextId = nextNodeId; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._nextId = nextNodeId; } private void SetSubTreeSize(int nodeId, int size) { Debug.Assert(nodeId != NIL && - (size != 0 || _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._selfId == NIL) && - (size != 1 || _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._nextId == NIL), "SetSize"); + (size != 0 || _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._selfId == NIL) && + (size != 1 || _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._nextId == NIL), "SetSize"); // this improves performance by reducing the impact of this heavily used method - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._subTreeSize = size; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._subTreeSize = size; VerifySize(nodeId, size); } @@ -1749,7 +1751,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].subTreeSize += 1; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._subTreeSize += 1; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._subTreeSize += 1; } @@ -1761,7 +1763,7 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].subTreeSize = myCorrectSize; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._subTreeSize = myCorrectSize; + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._subTreeSize = myCorrectSize; } private void DecreaseSize(int nodeId) @@ -1771,8 +1773,8 @@ namespace System.Data int slotIndex = nodeId & 0xFFFF; page.Slots[slotIndex].subTreeSize -= 1; */ - _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._subTreeSize -= 1; - VerifySize(nodeId, _pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._subTreeSize); + _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._subTreeSize -= 1; + VerifySize(nodeId, _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._subTreeSize); } [ConditionalAttribute("DEBUG")] @@ -1790,7 +1792,7 @@ namespace System.Data int rightId = page.Slots[slotIndex].rightId; return rightId; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._rightId); + return (_pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._rightId); } public int Left(int nodeId) @@ -1801,7 +1803,7 @@ namespace System.Data int leftId = page.Slots[slotIndex].leftId; return leftId; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._leftId); + return (_pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._leftId); } public int Parent(int nodeId) @@ -1812,7 +1814,7 @@ namespace System.Data int parentId = page.Slots[slotIndex].parentId; return parentId; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._parentId); + return (_pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._parentId); } private NodeColor color(int nodeId) @@ -1823,7 +1825,7 @@ namespace System.Data NodeColor col = page.Slots[slotIndex].nodeColor; return col; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._nodeColor); + return (_pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._nodeColor); } public int Next(int nodeId) @@ -1834,7 +1836,7 @@ namespace System.Data int nextId = page.Slots[slotIndex].nextId; return nextId; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._nextId); + return (_pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._nextId); } public int SubTreeSize(int nodeId) @@ -1845,7 +1847,7 @@ namespace System.Data int size = page.Slots[slotIndex].subTreeSize; return size; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._subTreeSize); + return (_pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._subTreeSize); } public K Key(int nodeId) @@ -1856,7 +1858,7 @@ namespace System.Data K key = page.Slots[slotIndex].keyOfNode; return key; */ - return (_pageTable[nodeId >> 16]._slots[nodeId & 0xFFFF]._keyOfNode); + return _pageTable[nodeId >> 16]!._slots[nodeId & 0xFFFF]._keyOfNode!; } private enum NodeColor @@ -1873,6 +1875,7 @@ namespace System.Data internal int _parentId; internal int _nextId; // multiple records associated with same key internal int _subTreeSize; // number of nodes in subtree rooted at the current node + [AllowNull, MaybeNull] internal K _keyOfNode; internal NodeColor _nodeColor; } @@ -2039,6 +2042,7 @@ namespace System.Data private readonly RBTree _tree; private readonly int _version; private int _index, _mainTreeNodeId; + [AllowNull, MaybeNull] private K _current; internal RBTreeEnumerator(RBTree tree) @@ -2090,11 +2094,12 @@ namespace System.Data { get { - return _current; + // TODO: Should throw if MoveNext hasn't been called + return _current!; } } - object IEnumerator.Current + object? IEnumerator.Current { get { diff --git a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs index cd7b7e0..daa5cc1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs @@ -15,7 +15,7 @@ namespace System.Data private int _recordCapacity; private readonly List _freeRecordList = new List(); - private DataRow[] _rows; + private DataRow?[] _rows = default!; // Always late-initialized by callers via NewRecordBase internal RecordManager(DataTable table) { @@ -121,7 +121,7 @@ namespace System.Data // Debug.Assert(record < lastFreeRecord, "Attempt to Free() record"); if (-1 != record) { - this[record] = null; + _rows[record] = null; int count = _table._columnCollection.Count; for (int i = 0; i < count; ++i) @@ -168,7 +168,7 @@ namespace System.Data _freeRecordList.Capacity = _freeRecordList.Count + _table.Rows.Count; for (int record = 0; record < _recordCapacity; ++record) { - if (_rows[record] != null && _rows[record].rowID != -1) + if (_rows[record] is { } row && row.rowID != -1) { int tempRecord = record; FreeRecord(ref tempRecord); @@ -182,7 +182,7 @@ namespace System.Data get { Debug.Assert(record >= 0 && record < _rows.Length, "Invalid record number"); - return _rows[record]; + return _rows[record]!; } set { @@ -225,11 +225,11 @@ namespace System.Data for (int i = 0; i < count; ++i) { DataColumn dstColumn = _table.Columns[i]; - DataColumn srcColumn = src.Columns[dstColumn.ColumnName]; + DataColumn? srcColumn = src.Columns[dstColumn.ColumnName]; if (null != srcColumn) { object value = srcColumn[record]; - ICloneable cloneableObject = value as ICloneable; + ICloneable? cloneableObject = value as ICloneable; if (null != cloneableObject) { dstColumn[newRecord] = cloneableObject.Clone(); @@ -267,14 +267,15 @@ namespace System.Data internal void VerifyRecord(int record) { Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accessing free record"); - Debug.Assert((null == _rows[record]) || - (record == _rows[record]._oldRecord) || - (record == _rows[record]._newRecord) || - (record == _rows[record]._tempRecord), "record of a different row"); + var r = _rows[record]; + Debug.Assert((null == r) || + (record == r._oldRecord) || + (record == r._newRecord) || + (record == r._tempRecord), "record of a different row"); } [Conditional("DEBUG")] - internal void VerifyRecord(int record, DataRow row) + internal void VerifyRecord(int record, DataRow? row) { Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accessing free record"); Debug.Assert((null == _rows[record]) || (row == _rows[record]), "record of a different row"); diff --git a/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs b/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs index ac23ef3..3a12193 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs @@ -7,10 +7,10 @@ namespace System.Data { internal sealed class RelatedView : DataView, IFilter { - private readonly Nullable _parentKey; + private readonly DataKey? _parentKey; private readonly DataKey _childKey; - private readonly DataRowView _parentRowView; - private readonly object[] _filterValues; + private readonly DataRowView? _parentRowView; + private readonly object[]? _filterValues; public RelatedView(DataColumn[] columns, object[] values) : base(columns[0].Table, false) { @@ -37,24 +37,24 @@ namespace System.Data base.ResetRowViewCache(); } - private object[] GetParentValues() + private object[]? GetParentValues() { if (_filterValues != null) { return _filterValues; } - if (!_parentRowView.HasRecord()) + if (!_parentRowView!.HasRecord()) { return null; } - return _parentKey.Value.GetKeyValues(_parentRowView.GetRecord()); + return _parentKey!.Value.GetKeyValues(_parentRowView.GetRecord()); } public bool Invoke(DataRow row, DataRowVersion version) { - object[] parentValues = GetParentValues(); + object[]? parentValues = GetParentValues(); if (parentValues == null) { return false; @@ -79,7 +79,7 @@ namespace System.Data } } - IFilter baseFilter = base.GetFilter(); + IFilter? baseFilter = base.GetFilter(); if (baseFilter != null) { allow &= baseFilter.Invoke(row, version); @@ -94,19 +94,19 @@ namespace System.Data public override DataRowView AddNew() { DataRowView addNewRowView = base.AddNew(); - addNewRowView.Row.SetKeyValues(_childKey, GetParentValues()); + addNewRowView.Row.SetKeyValues(_childKey, GetParentValues()!); return addNewRowView; } - internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter newRowFilter) + internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter? newRowFilter) { SetIndex2(newSort, newRowStates, newRowFilter, false); Reset(); } - public override bool Equals(DataView dv) + public override bool Equals(DataView? dv) { - RelatedView other = dv as RelatedView; + RelatedView? other = dv as RelatedView; if (other == null) { return false; @@ -127,12 +127,12 @@ namespace System.Data } return (CompareArray(_childKey.ColumnsReference, other._childKey.ColumnsReference) && - CompareArray(_parentKey.Value.ColumnsReference, _parentKey.Value.ColumnsReference) && - _parentRowView.Equals(other._parentRowView)); + CompareArray(_parentKey!.Value.ColumnsReference, _parentKey.Value.ColumnsReference) && + _parentRowView!.Equals(other._parentRowView)); } } - private bool CompareArray(object[] value1, object[] value2) + private bool CompareArray(object?[]? value1, object?[]? value2) { if (value1 == null || value2 == null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs index 4860062..a14f40e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs @@ -41,8 +41,8 @@ namespace System.Data throw new ArgumentNullException(nameof(destinationType)); } - System.Reflection.ConstructorInfo ctor = null; - object[] values = null; + System.Reflection.ConstructorInfo? ctor = null; + object[]? values = null; if (destinationType == typeof(InstanceDescriptor) && value is DataRelation) { @@ -53,7 +53,7 @@ namespace System.Data if (string.IsNullOrEmpty(parentTable.Namespace) && string.IsNullOrEmpty(childTable.Namespace)) { ctor = typeof(DataRelation).GetConstructor(new Type[] { typeof(string) /*relationName*/, typeof(string) /*parentTableName*/, typeof(string) /*childTableName */, - typeof(string[]) /*parentColumnNames */, typeof(string[]) /*childColumnNames*/, typeof(bool) /*nested*/ }); + typeof(string[]) /*parentColumnNames */, typeof(string[]) /*childColumnNames*/, typeof(bool) /*nested*/ })!; values = new object[] { rel.RelationName, rel.ParentKey.Table.TableName, rel.ChildKey.Table.TableName, rel.ParentColumnNames, rel.ChildColumnNames, rel.Nested }; } @@ -61,7 +61,7 @@ namespace System.Data { ctor = typeof(DataRelation).GetConstructor(new Type[] { typeof(string)/*relationName*/, typeof(string)/*parentTableName*/, typeof(string)/*parentTableNamespace*/, typeof(string)/*childTableName */, typeof(string)/*childTableNamespace */, - typeof(string[])/*parentColumnNames */, typeof(string[]) /*childColumnNames*/, typeof(bool) /*nested*/}); + typeof(string[])/*parentColumnNames */, typeof(string[]) /*childColumnNames*/, typeof(bool) /*nested*/})!; values = new object[] { rel.RelationName, rel.ParentKey.Table.TableName, rel.ParentKey.Table.Namespace, rel.ChildKey.Table.TableName, rel.ChildKey.Table.Namespace, rel.ParentColumnNames, rel.ChildColumnNames, rel.Nested }; diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs index d8c31f2..9d771f0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs @@ -14,7 +14,7 @@ namespace System.Data.SqlTypes public struct SqlBinary : INullable, IComparable, IXmlSerializable { // NOTE: If any instance fields change, update SqlTypeWorkarounds type in System.Data.SqlClient. - private byte[] _value; + private byte[]? _value; private SqlBinary(bool fNull) { @@ -24,7 +24,7 @@ namespace System.Data.SqlTypes /// /// Initializes a new instance of the class with a binary object to be stored. /// - public SqlBinary(byte[] value) + public SqlBinary(byte[]? value) { // if value is null, this generates a SqlBinary.Null if (value == null) @@ -41,7 +41,7 @@ namespace System.Data.SqlTypes /// /// Initializes a new instance of the class with a binary object to be stored. This constructor will not copy the value. /// - internal SqlBinary(byte[] value, bool ignored) + internal SqlBinary(byte[]? value, bool ignored) { // if value is null, this generates a SqlBinary.Null _value = value; @@ -51,7 +51,7 @@ namespace System.Data.SqlTypes /// /// Gets whether or not is null. /// - public bool IsNull => _value == null; + public bool IsNull => _value is null; // property: Value /// @@ -61,7 +61,7 @@ namespace System.Data.SqlTypes { get { - if (IsNull) + if (_value is null) { throw new SqlNullValueException(); } @@ -77,7 +77,7 @@ namespace System.Data.SqlTypes { get { - if (IsNull) + if (_value is null) { throw new SqlNullValueException(); } @@ -93,7 +93,7 @@ namespace System.Data.SqlTypes { get { - if (!IsNull) + if (_value != null) { return _value.Length; } @@ -113,13 +113,13 @@ namespace System.Data.SqlTypes /// /// Converts a to a binary object. /// - public static explicit operator byte[](SqlBinary x) => x.Value; + public static explicit operator byte[]?(SqlBinary x) => x.Value; /// /// Returns a string describing a object. /// public override string ToString() => - IsNull ? SQLResource.NullString : "SqlBinary(" + _value.Length.ToString(CultureInfo.InvariantCulture) + ")"; + _value is null ? SQLResource.NullString : "SqlBinary(" + _value.Length.ToString(CultureInfo.InvariantCulture) + ")"; // Unary operators @@ -336,7 +336,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlBinary) { @@ -344,7 +344,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlBinary)); + throw ADP.WrongType(value!.GetType(), typeof(SqlBinary)); } public int CompareTo(SqlBinary value) @@ -362,7 +362,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlBinary)) { @@ -409,7 +409,7 @@ namespace System.Data.SqlTypes // For hashing purpose public override int GetHashCode() { - if (IsNull) + if (_value is null) return 0; //First trim off extra '\0's @@ -420,7 +420,7 @@ namespace System.Data.SqlTypes return HashByteArray(_value, cbLen); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { @@ -456,7 +456,7 @@ namespace System.Data.SqlTypes void IXmlSerializable.WriteXml(XmlWriter writer) { - if (IsNull) + if (_value is null) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs index c681937..932d7c1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs @@ -193,7 +193,7 @@ namespace System.Data.SqlTypes { if (null == s) // Let Boolean.Parse throw exception - return new SqlBoolean(bool.Parse(s)); + return new SqlBoolean(bool.Parse(s!)); if (s == SQLResource.NullString) return SqlBoolean.Null; @@ -438,7 +438,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlBoolean) { @@ -446,7 +446,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlBoolean)); + throw ADP.WrongType(value!.GetType(), typeof(SqlBoolean)); } public int CompareTo(SqlBoolean value) @@ -464,7 +464,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlBoolean)) { @@ -485,7 +485,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs index 5767393..060ae2b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs @@ -70,7 +70,7 @@ namespace System.Data.SqlTypes public override string ToString() { - return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); + return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null!); } public static SqlByte Parse(string s) @@ -447,7 +447,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlByte) { @@ -455,7 +455,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlByte)); + throw ADP.WrongType(value!.GetType(), typeof(SqlByte)); } public int CompareTo(SqlByte value) @@ -473,7 +473,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlByte)) { @@ -494,7 +494,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs index b98d5a3..14d1fa1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs @@ -42,12 +42,12 @@ namespace System.Data.SqlTypes // - m_lCurLen must be x_lNull. // 5) SqlBytes contains a Lazy Materialized Blob (ie, StorageState.Delayed) // - internal byte[] _rgbBuf; // Data buffer + internal byte[]? _rgbBuf; // Data buffer private long _lCurLen; // Current data length - internal Stream _stream; + internal Stream? _stream; private SqlBytesCharsState _state; - private byte[] _rgbWorkBuf; // A 1-byte work buffer. + private byte[]? _rgbWorkBuf; // A 1-byte work buffer. // The max data length that we support at this time. private const long x_lMaxLen = int.MaxValue; @@ -65,7 +65,7 @@ namespace System.Data.SqlTypes } // Create a SqlBytes with an in-memory buffer - public SqlBytes(byte[] buffer) + public SqlBytes(byte[]? buffer) { _rgbBuf = buffer; _stream = null; @@ -86,11 +86,11 @@ namespace System.Data.SqlTypes } // Create a SqlBytes from a SqlBinary - public SqlBytes(SqlBinary value) : this(value.IsNull ? null : value.Value) + public SqlBytes(SqlBinary value) : this(value.IsNull ? null : value.Value!) { } - public SqlBytes(Stream s) + public SqlBytes(Stream? s) { // Create a SqlBytes from a Stream _rgbBuf = null; @@ -119,7 +119,7 @@ namespace System.Data.SqlTypes // Property: the in-memory buffer of SqlBytes // Return Buffer even if SqlBytes is Null. - public byte[] Buffer + public byte[]? Buffer { get { @@ -139,7 +139,7 @@ namespace System.Data.SqlTypes return _state switch { SqlBytesCharsState.Null => throw new SqlNullValueException(), - SqlBytesCharsState.Stream => _stream.Length, + SqlBytesCharsState.Stream => _stream!.Length, _ => _lCurLen, }; } @@ -174,7 +174,7 @@ namespace System.Data.SqlTypes throw new SqlNullValueException(); case SqlBytesCharsState.Stream: - if (_stream.Length > x_lMaxLen) + if (_stream!.Length > x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); buffer = new byte[_stream.Length]; if (_stream.Position != 0) @@ -184,7 +184,7 @@ namespace System.Data.SqlTypes default: buffer = new byte[_lCurLen]; - Array.Copy(_rgbBuf, buffer, (int)_lCurLen); + Array.Copy(_rgbBuf!, buffer, (int)_lCurLen); break; } @@ -233,7 +233,7 @@ namespace System.Data.SqlTypes { get { - return FStream() ? _stream : new StreamOnSqlBytes(this); + return FStream() ? _stream! : new StreamOnSqlBytes(this); } set { @@ -266,7 +266,7 @@ namespace System.Data.SqlTypes if (FStream()) { - _stream.SetLength(value); + _stream!.SetLength(value); } else { @@ -319,13 +319,13 @@ namespace System.Data.SqlTypes switch (_state) { case SqlBytesCharsState.Stream: - if (_stream.Position != offset) + if (_stream!.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Read(buffer, offsetInBuffer, count); break; default: - Array.Copy(_rgbBuf, offset, buffer, offsetInBuffer, count); + Array.Copy(_rgbBuf!, offset, buffer, offsetInBuffer, count); break; } } @@ -337,7 +337,7 @@ namespace System.Data.SqlTypes { if (FStream()) { - if (_stream.Position != offset) + if (_stream!.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Write(buffer, offsetInBuffer, count); } @@ -450,7 +450,7 @@ namespace System.Data.SqlTypes { Debug.Assert(FStream()); - long lStreamLen = _stream.Length; + long lStreamLen = _stream!.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); @@ -475,7 +475,7 @@ namespace System.Data.SqlTypes return _state == SqlBytesCharsState.Stream; } - private void SetBuffer(byte[] buffer) + private void SetBuffer(byte[]? buffer) { _rgbBuf = buffer; _lCurLen = (_rgbBuf == null) ? x_lNull : _rgbBuf.Length; @@ -489,14 +489,14 @@ namespace System.Data.SqlTypes // XML Serialization // -------------------------------------------------------------- - XmlSchema IXmlSerializable.GetSchema() + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { - byte[] value = null; + byte[]? value = null; string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); @@ -534,7 +534,7 @@ namespace System.Data.SqlTypes } else { - byte[] value = Buffer; + byte[] value = Buffer!; writer.WriteString(Convert.ToBase64String(value, 0, (int)(Length))); } } @@ -566,7 +566,7 @@ namespace System.Data.SqlTypes { get { - return new SqlBytes((byte[])null); + return new SqlBytes((byte[]?)null); } } } // class SqlBytes @@ -760,7 +760,7 @@ namespace System.Data.SqlTypes public override void Flush() { if (_sb.FStream()) - _sb._stream.Flush(); + _sb._stream!.Flush(); } protected override void Dispose(bool disposing) @@ -770,7 +770,7 @@ namespace System.Data.SqlTypes // This is the only case that m_sb is null. try { - _sb = null; + _sb = null!; } finally { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs index bf1b5ae..b7ae23b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs @@ -34,12 +34,12 @@ namespace System.Data.SqlTypes // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed) // - internal char[] _rgchBuf; // Data buffer + internal char[]? _rgchBuf; // Data buffer private long _lCurLen; // Current data length - internal SqlStreamChars _stream; + internal SqlStreamChars? _stream; private SqlBytesCharsState _state; - private char[] _rgchWorkBuf; // A 1-char work buffer. + private char[]? _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = int.MaxValue; @@ -57,7 +57,7 @@ namespace System.Data.SqlTypes } // Create a SqlChars with an in-memory buffer - public SqlChars(char[] buffer) + public SqlChars(char[]? buffer) { _rgchBuf = buffer; _stream = null; @@ -111,7 +111,7 @@ namespace System.Data.SqlTypes // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. - public char[] Buffer + public char[]? Buffer { get { @@ -131,7 +131,7 @@ namespace System.Data.SqlTypes return _state switch { SqlBytesCharsState.Null => throw new SqlNullValueException(), - SqlBytesCharsState.Stream => _stream.Length, + SqlBytesCharsState.Stream => _stream!.Length, _ => _lCurLen, }; } @@ -168,7 +168,7 @@ namespace System.Data.SqlTypes throw new SqlNullValueException(); case SqlBytesCharsState.Stream: - if (_stream.Length > x_lMaxLen) + if (_stream!.Length > x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); buffer = new char[_stream.Length]; if (_stream.Position != 0) @@ -178,7 +178,7 @@ namespace System.Data.SqlTypes default: buffer = new char[_lCurLen]; - Array.Copy(_rgchBuf, buffer, (int)_lCurLen); + Array.Copy(_rgchBuf!, buffer, (int)_lCurLen); break; } @@ -214,7 +214,7 @@ namespace System.Data.SqlTypes { get { - return FStream() ? _stream : new SqlStreamChars(this); + return FStream() ? _stream! : new SqlStreamChars(this); } set { @@ -262,7 +262,7 @@ namespace System.Data.SqlTypes if (FStream()) { - _stream.SetLength(value); + _stream!.SetLength(value); } else { @@ -316,13 +316,13 @@ namespace System.Data.SqlTypes switch (_state) { case SqlBytesCharsState.Stream: - if (_stream.Position != offset) + if (_stream!.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Read(buffer, offsetInBuffer, count); break; default: - Array.Copy(_rgchBuf, offset, buffer, offsetInBuffer, count); + Array.Copy(_rgchBuf!, offset, buffer, offsetInBuffer, count); break; } } @@ -335,7 +335,7 @@ namespace System.Data.SqlTypes { if (FStream()) { - if (_stream.Position != offset) + if (_stream!.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Write(buffer, offsetInBuffer, count); } @@ -454,7 +454,7 @@ namespace System.Data.SqlTypes { Debug.Assert(FStream()); - long lStreamLen = _stream.Length; + long lStreamLen = _stream!.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); @@ -487,14 +487,14 @@ namespace System.Data.SqlTypes // -------------------------------------------------------------- - XmlSchema IXmlSerializable.GetSchema() + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { - char[] value = null; + char[]? value = null; string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); @@ -519,7 +519,7 @@ namespace System.Data.SqlTypes } else { - char[] value = Buffer; + char[] value = Buffer!; writer.WriteString(new string(value, 0, (int)(Length))); } } @@ -550,7 +550,7 @@ namespace System.Data.SqlTypes { get { - return new SqlChars((char[])null); + return new SqlChars((char[]?)null); } } } // class SqlChars diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs index 82e9760..6126c74 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs @@ -339,7 +339,7 @@ namespace System.Data.SqlTypes if (IsNull) return SQLResource.NullString; DateTime dateTime = ToDateTime(this); - return dateTime.ToString((IFormatProvider)null); + return dateTime.ToString((IFormatProvider)null!); } public static SqlDateTime Parse(string s) @@ -355,7 +355,7 @@ namespace System.Data.SqlTypes } catch (FormatException) { - DateTimeFormatInfo dtfi = (DateTimeFormatInfo)(CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo))); + DateTimeFormatInfo dtfi = (DateTimeFormatInfo)(CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo)))!; dt = DateTime.ParseExact(s, s_dateTimeFormats, dtfi, x_DateTimeStyle); } @@ -594,7 +594,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlDateTime) { @@ -602,7 +602,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlDateTime)); + throw ADP.WrongType(value!.GetType(), typeof(SqlDateTime)); } public int CompareTo(SqlDateTime value) @@ -620,7 +620,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlDateTime)) { @@ -641,7 +641,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs index b061deb..2fd011c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs @@ -3255,13 +3255,13 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlDecimal i) { return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlDecimal)); + throw ADP.WrongType(value!.GetType(), typeof(SqlDecimal)); } public int CompareTo(SqlDecimal value) @@ -3279,7 +3279,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlDecimal)) { @@ -3330,7 +3330,7 @@ namespace System.Data.SqlTypes return ulValue; } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs index 7e86f7e..968f5cb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs @@ -76,7 +76,7 @@ namespace System.Data.SqlTypes public override string ToString() { - return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); + return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null!); } public static SqlDouble Parse(string s) @@ -363,7 +363,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlDouble) { @@ -371,7 +371,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlDouble)); + throw ADP.WrongType(value!.GetType(), typeof(SqlDouble)); } public int CompareTo(SqlDouble value) @@ -389,7 +389,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlDouble)) { @@ -410,7 +410,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs index 71dfdba..0a87708 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs @@ -24,7 +24,7 @@ namespace System.Data.SqlTypes {10, 11, 12, 13, 14, 15, 8, 9, 6, 7, 4, 5, 0, 1, 2, 3}; // NOTE: If any instance fields change, update SqlTypeWorkarounds type in System.Data.SqlClient. - private byte[] m_value; // the SqlGuid is null if m_value is null + private byte[]? m_value; // the SqlGuid is null if m_value is null // constructor // construct a SqlGuid.Null @@ -69,7 +69,7 @@ namespace System.Data.SqlTypes // INullable public bool IsNull { - get { return (m_value == null); } + get { return (m_value is null); } } // property: Value @@ -77,7 +77,7 @@ namespace System.Data.SqlTypes { get { - if (IsNull) + if (m_value is null) throw new SqlNullValueException(); else return new Guid(m_value); @@ -96,16 +96,16 @@ namespace System.Data.SqlTypes return x.Value; } - public byte[] ToByteArray() + public byte[]? ToByteArray() { byte[] ret = new byte[SizeOfGuid]; - m_value.CopyTo(ret, 0); + m_value!.CopyTo(ret, 0); // TODO: NRE return ret; } public override string ToString() { - if (IsNull) + if (m_value is null) return SQLResource.NullString; Guid g = new Guid(m_value); @@ -129,8 +129,8 @@ namespace System.Data.SqlTypes { byte b1, b2; - b1 = x.m_value[s_rgiGuidOrder[i]]; - b2 = y.m_value[s_rgiGuidOrder[i]]; + b1 = x.m_value![s_rgiGuidOrder[i]]; + b2 = y.m_value![s_rgiGuidOrder[i]]; if (b1 != b2) return (b1 < b2) ? EComparison.LT : EComparison.GT; } @@ -254,7 +254,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlGuid) { @@ -262,7 +262,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlGuid)); + throw ADP.WrongType(value!.GetType(), typeof(SqlGuid)); } public int CompareTo(SqlGuid value) @@ -280,7 +280,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlGuid)) { @@ -301,7 +301,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { @@ -320,7 +320,7 @@ namespace System.Data.SqlTypes void IXmlSerializable.WriteXml(XmlWriter writer) { - if (IsNull) + if (m_value is null) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs index ccd47ae..3444f17 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs @@ -69,7 +69,7 @@ namespace System.Data.SqlTypes public override string ToString() { - return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); + return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null!); } public static SqlInt16 Parse(string s) @@ -448,7 +448,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlInt16) { @@ -456,7 +456,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlInt16)); + throw ADP.WrongType(value!.GetType(), typeof(SqlInt16)); } public int CompareTo(SqlInt16 value) @@ -474,7 +474,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlInt16)) { @@ -495,7 +495,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs index c8ea61e..c9c06b2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs @@ -70,7 +70,7 @@ namespace System.Data.SqlTypes public override string ToString() { - return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); + return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null!); } public static SqlInt32 Parse(string s) @@ -463,7 +463,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlInt32) { @@ -471,7 +471,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlInt32)); + throw ADP.WrongType(value!.GetType(), typeof(SqlInt32)); } public int CompareTo(SqlInt32 value) @@ -489,7 +489,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlInt32)) { @@ -510,7 +510,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs index cff3272..c4508d6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs @@ -71,7 +71,7 @@ namespace System.Data.SqlTypes public override string ToString() { - return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); + return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null!); } public static SqlInt64 Parse(string s) @@ -522,7 +522,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlInt64) { @@ -530,7 +530,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlInt64)); + throw ADP.WrongType(value!.GetType(), typeof(SqlInt64)); } public int CompareTo(SqlInt64 value) @@ -548,7 +548,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlInt64)) { @@ -569,7 +569,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs index d8ddab1..5e722de 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs @@ -512,7 +512,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlMoney) { @@ -520,7 +520,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlMoney)); + throw ADP.WrongType(value!.GetType(), typeof(SqlMoney)); } public int CompareTo(SqlMoney value) @@ -538,7 +538,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlMoney)) { @@ -560,7 +560,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : _value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs index cf0999b..8798deb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs @@ -77,7 +77,7 @@ namespace System.Data.SqlTypes public override string ToString() { - return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null); + return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null!); } public static SqlSingle Parse(string s) @@ -373,7 +373,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlSingle) { @@ -381,7 +381,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlSingle)); + throw ADP.WrongType(value!.GetType(), typeof(SqlSingle)); } public int CompareTo(SqlSingle value) @@ -399,7 +399,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlSingle)) { @@ -420,7 +420,7 @@ namespace System.Data.SqlTypes return IsNull ? 0 : Value.GetHashCode(); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs index f33028f..b85a913 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs @@ -35,8 +35,8 @@ namespace System.Data.SqlTypes [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SqlString : INullable, IComparable, IXmlSerializable { - private string m_value; // Do not rename (binary serialization) - private CompareInfo m_cmpInfo; // Do not rename (binary serialization) + private string? m_value; // Do not rename (binary serialization) + private CompareInfo? m_cmpInfo; // Do not rename (binary serialization) private readonly int m_lcid; // Locale Id. Do not rename (binary serialization) private readonly SqlCompareOptions m_flag; // Compare flags. Do not rename (binary serialization) private bool m_fNotNull; // false if null. Do not rename (binary serialization) @@ -99,7 +99,7 @@ namespace System.Data.SqlTypes /// /// Initializes a new instance of the class. /// - public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count, bool fUnicode) + public SqlString(int lcid, SqlCompareOptions compareOptions, byte[]? data, int index, int count, bool fUnicode) { m_lcid = lcid; ValidateSqlCompareOptions(compareOptions); @@ -143,7 +143,7 @@ namespace System.Data.SqlTypes /// /// Initializes a new instance of the class. /// - public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count) + public SqlString(int lcid, SqlCompareOptions compareOptions, byte[]? data, int index, int count) : this(lcid, compareOptions, data, index, count, true) { } @@ -159,7 +159,7 @@ namespace System.Data.SqlTypes /// /// Initializes a new instance of the class. /// - public SqlString(string data, int lcid, SqlCompareOptions compareOptions) + public SqlString(string? data, int lcid, SqlCompareOptions compareOptions) { m_lcid = lcid; ValidateSqlCompareOptions(compareOptions); @@ -180,18 +180,18 @@ namespace System.Data.SqlTypes /// /// Initializes a new instance of the class. /// - public SqlString(string data, int lcid) : this(data, lcid, s_iDefaultFlag) + public SqlString(string? data, int lcid) : this(data, lcid, s_iDefaultFlag) { } /// /// Initializes a new instance of the class. /// - public SqlString(string data) : this(data, System.Globalization.CultureInfo.CurrentCulture.LCID, s_iDefaultFlag) + public SqlString(string? data) : this(data, System.Globalization.CultureInfo.CurrentCulture.LCID, s_iDefaultFlag) { } - private SqlString(int lcid, SqlCompareOptions compareOptions, string data, CompareInfo cmpInfo) + private SqlString(int lcid, SqlCompareOptions compareOptions, string? data, CompareInfo? cmpInfo) { m_lcid = lcid; ValidateSqlCompareOptions(compareOptions); @@ -229,7 +229,7 @@ namespace System.Data.SqlTypes get { if (!IsNull) - return m_value; + return m_value!; else throw new SqlNullValueException(); } @@ -271,7 +271,7 @@ namespace System.Data.SqlTypes if (!IsNull) { SetCompareInfo(); - return m_cmpInfo; + return m_cmpInfo!; } else throw new SqlNullValueException(); @@ -306,18 +306,18 @@ namespace System.Data.SqlTypes /// public override string ToString() { - return IsNull ? SQLResource.NullString : m_value; + return IsNull ? SQLResource.NullString : m_value!; } - public byte[] GetUnicodeBytes() + public byte[]? GetUnicodeBytes() { if (IsNull) return null; - return s_unicodeEncoding.GetBytes(m_value); + return s_unicodeEncoding.GetBytes(m_value!); } - public byte[] GetNonUnicodeBytes() + public byte[]? GetNonUnicodeBytes() { if (IsNull) return null; @@ -326,7 +326,7 @@ namespace System.Data.SqlTypes CultureInfo culInfo = new CultureInfo(m_lcid); Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage); - return cpe.GetBytes(m_value); + return cpe.GetBytes(m_value!); } /* @@ -382,8 +382,8 @@ namespace System.Data.SqlTypes // Trim the trailing space for comparison // Avoid using String.TrimEnd function to avoid extra string allocations - string rgchX = x.m_value; - string rgchY = y.m_value; + string rgchX = x.m_value!; + string rgchY = y.m_value!; int cwchX = rgchX.Length; int cwchY = rgchY.Length; @@ -394,7 +394,7 @@ namespace System.Data.SqlTypes CompareOptions options = CompareOptionsFromSqlCompareOptions(x.m_flag); - iCmpResult = x.m_cmpInfo.Compare(x.m_value, 0, cwchX, y.m_value, 0, cwchY, options); + iCmpResult = x.m_cmpInfo!.Compare(x.m_value, 0, cwchX, y.m_value, 0, cwchY, options); } return iCmpResult; @@ -457,37 +457,37 @@ namespace System.Data.SqlTypes // Explicit conversion from SqlByte to SqlString public static explicit operator SqlString(SqlByte x) { - return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null)); + return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null!)); } // Explicit conversion from SqlInt16 to SqlString public static explicit operator SqlString(SqlInt16 x) { - return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null)); + return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null!)); } // Explicit conversion from SqlInt32 to SqlString public static explicit operator SqlString(SqlInt32 x) { - return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null)); + return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null!)); } // Explicit conversion from SqlInt64 to SqlString public static explicit operator SqlString(SqlInt64 x) { - return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null)); + return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null!)); } // Explicit conversion from SqlSingle to SqlString public static explicit operator SqlString(SqlSingle x) { - return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null)); + return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null!)); } // Explicit conversion from SqlDouble to SqlString public static explicit operator SqlString(SqlDouble x) { - return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null)); + return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null!)); } // Explicit conversion from SqlDecimal to SqlString @@ -520,7 +520,7 @@ namespace System.Data.SqlTypes return new SqlString(true); else { - SqlString ret = new SqlString(m_value, m_lcid, m_flag); + SqlString ret = new SqlString(m_value!, m_lcid, m_flag); return ret; } } @@ -712,8 +712,8 @@ namespace System.Data.SqlTypes // Does a memory comparison. private static int CompareBinary(SqlString x, SqlString y) { - byte[] rgDataX = s_unicodeEncoding.GetBytes(x.m_value); - byte[] rgDataY = s_unicodeEncoding.GetBytes(y.m_value); + byte[] rgDataX = s_unicodeEncoding.GetBytes(x.m_value!); + byte[] rgDataY = s_unicodeEncoding.GetBytes(y.m_value!); int cbX = rgDataX.Length; int cbY = rgDataY.Length; int cbMin = cbX < cbY ? cbX : cbY; @@ -768,8 +768,8 @@ namespace System.Data.SqlTypes { Debug.Assert(!x.IsNull && !y.IsNull); - string rgDataX = x.m_value; - string rgDataY = y.m_value; + string rgDataX = x.m_value!; + string rgDataY = y.m_value!; int cwchX = rgDataX.Length; int cwchY = rgDataY.Length; int cwchMin = cwchX < cwchY ? cwchX : cwchY; @@ -833,7 +833,7 @@ namespace System.Data.SqlTypes // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. - public int CompareTo(object value) + public int CompareTo(object? value) { if (value is SqlString) { @@ -841,7 +841,7 @@ namespace System.Data.SqlTypes return CompareTo(i); } - throw ADP.WrongType(value.GetType(), typeof(SqlString)); + throw ADP.WrongType(value!.GetType(), typeof(SqlString)); } public int CompareTo(SqlString value) @@ -870,7 +870,7 @@ namespace System.Data.SqlTypes } // Compares this instance with a specified object - public override bool Equals(object value) + public override bool Equals(object? value) { if (!(value is SqlString)) { @@ -893,7 +893,7 @@ namespace System.Data.SqlTypes byte[] rgbSortKey; if (FBinarySort()) - rgbSortKey = s_unicodeEncoding.GetBytes(m_value.TrimEnd()); + rgbSortKey = s_unicodeEncoding.GetBytes(m_value!.TrimEnd()); else { // GetHashCode should not throw just because this instance has an invalid LCID or compare options. @@ -902,7 +902,7 @@ namespace System.Data.SqlTypes try { SetCompareInfo(); - cmpInfo = m_cmpInfo; + cmpInfo = m_cmpInfo!; options = CompareOptionsFromSqlCompareOptions(m_flag); } catch (ArgumentException) @@ -912,13 +912,13 @@ namespace System.Data.SqlTypes cmpInfo = CultureInfo.InvariantCulture.CompareInfo; options = CompareOptions.None; } - rgbSortKey = cmpInfo.GetSortKey(m_value.TrimEnd(), options).KeyData; + rgbSortKey = cmpInfo.GetSortKey(m_value!.TrimEnd(), options).KeyData; } return SqlBinary.HashByteArray(rgbSortKey, rgbSortKey.Length); } - XmlSchema IXmlSerializable.GetSchema() { return null; } + XmlSchema? IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs index 073644d..eeff48c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLUtility.cs @@ -32,11 +32,11 @@ namespace System.Data.SqlTypes } // Creates a new SqlTypeException with its message string set to message. - public SqlTypeException(string message) : this(message, null) + public SqlTypeException(string? message) : this(message, null) { } - public SqlTypeException(string message, Exception e) : base(message, e) + public SqlTypeException(string? message, Exception? e) : base(message, e) { HResult = HResults.SqlType; } @@ -45,15 +45,15 @@ namespace System.Data.SqlTypes { } - private static SerializationInfo SqlTypeExceptionSerialization(SerializationInfo si, StreamingContext sc) + private static SerializationInfo SqlTypeExceptionSerialization(SerializationInfo? si, StreamingContext sc) { if ((null != si) && (1 == si.MemberCount)) { - string message = si.GetString("SqlTypeExceptionMessage"); + string? message = si.GetString("SqlTypeExceptionMessage"); SqlTypeException fakeValue = new SqlTypeException(message); fakeValue.GetObjectData(si, sc); } - return si; + return si!; } } @@ -67,11 +67,11 @@ namespace System.Data.SqlTypes } // Creates a new NullValueException with its message string set to message. - public SqlNullValueException(string message) : this(message, null) + public SqlNullValueException(string? message) : this(message, null) { } - public SqlNullValueException(string message, Exception e) : base(message, e) + public SqlNullValueException(string? message, Exception? e) : base(message, e) { HResult = HResults.SqlNullValue; } @@ -84,11 +84,11 @@ namespace System.Data.SqlTypes { if ((null != si) && (1 == si.MemberCount)) { - string message = si.GetString("SqlNullValueExceptionMessage"); + string? message = si.GetString("SqlNullValueExceptionMessage"); SqlNullValueException fakeValue = new SqlNullValueException(message); fakeValue.GetObjectData(si, sc); } - return si; + return si!; } } @@ -102,11 +102,11 @@ namespace System.Data.SqlTypes } // Creates a new SqlTruncateException with its message string set to message. - public SqlTruncateException(string message) : this(message, null) + public SqlTruncateException(string? message) : this(message, null) { } - public SqlTruncateException(string message, Exception e) : base(message, e) + public SqlTruncateException(string? message, Exception? e) : base(message, e) { HResult = HResults.SqlTruncate; } @@ -119,11 +119,11 @@ namespace System.Data.SqlTypes { if ((null != si) && (1 == si.MemberCount)) { - string message = si.GetString("SqlTruncateExceptionMessage"); + string? message = si.GetString("SqlTruncateExceptionMessage"); SqlTruncateException fakeValue = new SqlTruncateException(message); fakeValue.GetObjectData(si, sc); } - return si; + return si!; } } @@ -137,11 +137,11 @@ namespace System.Data.SqlTypes } // Creates a new NullValueException with its message string set to message. - public SqlNotFilledException(string message) : this(message, null) + public SqlNotFilledException(string? message) : this(message, null) { } - public SqlNotFilledException(string message, Exception e) : base(message, e) + public SqlNotFilledException(string? message, Exception? e) : base(message, e) { HResult = HResults.SqlNullValue; } @@ -161,11 +161,11 @@ namespace System.Data.SqlTypes } // Creates a new NullValueException with its message string set to message. - public SqlAlreadyFilledException(string message) : this(message, null) + public SqlAlreadyFilledException(string? message) : this(message, null) { } - public SqlAlreadyFilledException(string message, Exception e) : base(message, e) + public SqlAlreadyFilledException(string? message, Exception? e) : base(message, e) { HResult = HResults.SqlNullValue; } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs index 099c25e..7af1333 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs @@ -16,14 +16,14 @@ namespace System.Data.SqlTypes [XmlSchemaProvider("GetXsdType")] public sealed class SqlXml : INullable, IXmlSerializable { - private static readonly Func s_sqlReaderDelegate = CreateSqlReaderDelegate(); + private static readonly Func s_sqlReaderDelegate = CreateSqlReaderDelegate(); private static readonly XmlReaderSettings s_defaultXmlReaderSettings = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }; private static readonly XmlReaderSettings s_defaultXmlReaderSettingsCloseInput = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true }; - private static MethodInfo s_createSqlReaderMethodInfo; - private MethodInfo _createSqlReaderMethodInfo; + private static MethodInfo? s_createSqlReaderMethodInfo; + private MethodInfo? _createSqlReaderMethodInfo; private bool _fNotNull; // false if null, the default ctor (plain 0) will make it Null - private Stream _stream; + private Stream? _stream; private bool _firstCreateReader; public SqlXml() @@ -38,7 +38,7 @@ namespace System.Data.SqlTypes SetNull(); } - public SqlXml(XmlReader value) + public SqlXml(XmlReader? value) { // whoever pass in the XmlReader is responsible for closing it if (value == null) @@ -53,7 +53,7 @@ namespace System.Data.SqlTypes } } - public SqlXml(Stream value) + public SqlXml(Stream? value) { // whoever pass in the stream is responsible for closing it // similar to SqlBytes implementation @@ -76,7 +76,7 @@ namespace System.Data.SqlTypes throw new SqlNullValueException(); } - SqlXmlStreamWrapper stream = new SqlXmlStreamWrapper(_stream); + SqlXmlStreamWrapper stream = new SqlXmlStreamWrapper(_stream!); // if it is the first time we create reader and stream does not support CanSeek, no need to reset position if ((!_firstCreateReader || stream.CanSeek) && stream.Position != 0) @@ -118,11 +118,11 @@ namespace System.Data.SqlTypes } } - private static Func CreateSqlReaderDelegate() + private static Func CreateSqlReaderDelegate() { Debug.Assert(CreateSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null."); - return CreateSqlReaderMethodInfo.CreateDelegate>(); + return CreateSqlReaderMethodInfo.CreateDelegate>(); } private static MethodInfo CreateSqlReaderMethodInfo @@ -131,7 +131,7 @@ namespace System.Data.SqlTypes { if (s_createSqlReaderMethodInfo == null) { - s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic); + s_createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic)!; } return s_createSqlReaderMethodInfo; @@ -151,7 +151,7 @@ namespace System.Data.SqlTypes if (IsNull) throw new SqlNullValueException(); - StringWriter sw = new StringWriter((System.IFormatProvider)null); + StringWriter sw = new StringWriter((System.IFormatProvider)null!); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; @@ -213,7 +213,7 @@ namespace System.Data.SqlTypes return writerStream; } - XmlSchema IXmlSerializable.GetSchema() + XmlSchema? IXmlSerializable.GetSchema() { return null; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 49ff56c..8dbd298 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -12,29 +12,29 @@ namespace System.Data private readonly DataTable _table; private readonly IndexField[] _indexFields; private readonly DataViewRowState _recordStates; - private readonly DataExpression _rowFilter; - private readonly ExpressionNode _expression; + private readonly DataExpression? _rowFilter; + private readonly ExpressionNode? _expression; - private Index _index; + private Index? _index; - private int[] _records; + private int[]? _records; private int _recordCount; - private ExpressionNode _linearExpression; + private ExpressionNode? _linearExpression; private bool _candidatesForBinarySearch; private sealed class ColumnInfo { public bool flag; // Misc. Use public bool equalsOperator; // True when the associated expr has = Operator defined - public BinaryNode expr; // Binary Search capable expression associated + public BinaryNode? expr; // Binary Search capable expression associated } - private ColumnInfo[] _candidateColumns; + private ColumnInfo[]? _candidateColumns; private int _nCandidates; private int _matchedCandidates; - public Select(DataTable table, string filterExpression, string sort, DataViewRowState recordStates) + public Select(DataTable table, string? filterExpression, string? sort, DataViewRowState recordStates) { _table = table; _indexFields = table.ParseSortString(sort); @@ -54,6 +54,8 @@ namespace System.Data // Gathers all linear expressions in to this.linearExpression and all binary expressions in to their respective candidate columns expressions private void AnalyzeExpression(BinaryNode expr) { + Debug.Assert(_candidateColumns != null); + if (_linearExpression == _expression) return; @@ -75,7 +77,7 @@ namespace System.Data } else { - UnaryNode unaryNode = expr._left as UnaryNode; + UnaryNode? unaryNode = expr._left as UnaryNode; if (unaryNode != null) { while (unaryNode._op == Operators.Noop && unaryNode._right is UnaryNode && ((UnaryNode)unaryNode._right)._op == Operators.Noop) @@ -103,7 +105,7 @@ namespace System.Data } else { - UnaryNode unaryNode = expr._right as UnaryNode; + UnaryNode? unaryNode = expr._right as UnaryNode; if (unaryNode != null) { while (unaryNode._op == Operators.Noop && unaryNode._right is UnaryNode && ((UnaryNode)unaryNode._right)._op == Operators.Noop) @@ -135,7 +137,7 @@ namespace System.Data { if (expr._left is NameNode && expr._right is ConstNode) { - ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column.Ordinal]; + ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column!.Ordinal]; canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr)); if (expr._op == Operators.EqualTo) { @@ -158,7 +160,7 @@ namespace System.Data case Operators.LessOrEqual: expr._op = Operators.GreaterOrEqual; break; default: break; } - ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column.Ordinal]; + ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column!.Ordinal]; canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr)); if (expr._op == Operators.EqualTo) { @@ -175,6 +177,8 @@ namespace System.Data private bool CompareSortIndexDesc(IndexField[] fields) { + Debug.Assert(_candidateColumns != null); + if (fields.Length < _indexFields.Length) return false; int j = 0; @@ -227,6 +231,8 @@ namespace System.Data // Returns no. of columns that are matched private int CompareClosestCandidateIndexDesc(IndexField[] fields) { + Debug.Assert(_candidateColumns != null); + int count = (fields.Length < _nCandidates ? fields.Length : _nCandidates); int i = 0; for (; i < count; i++) @@ -304,6 +310,8 @@ namespace System.Data // Based on the required sorting and candidate columns settings, create a new index; Should be called only when there is no existing index to be reused private void CreateIndex() { + Debug.Assert(_candidateColumns != null); + if (_index == null) { if (_nCandidates == 0) @@ -441,9 +449,9 @@ namespace System.Data } - private bool IsOperatorIn(ExpressionNode enode) + private bool IsOperatorIn(ExpressionNode? enode) { - BinaryNode bnode = (enode as BinaryNode); + BinaryNode? bnode = (enode as BinaryNode); if (null != bnode) { if (Operators.In == bnode._op || @@ -461,8 +469,10 @@ namespace System.Data // Based on the current index and candidate columns settings, build the linear expression; Should be called only when there is atleast something for Binary Searching private void BuildLinearExpression() { + Debug.Assert(_candidateColumns != null); + int i; - IndexField[] fields = _index._indexFields; + IndexField[] fields = _index!._indexFields; int lenId = fields.Length; Debug.Assert(_matchedCandidates > 0 && _matchedCandidates <= lenId, "BuildLinearExpression : Invalid Index"); for (i = 0; i < _matchedCandidates; i++) @@ -481,9 +491,9 @@ namespace System.Data { if (!_candidateColumns[i].flag) { - if (_candidateColumns[i].expr != null) + if (_candidateColumns[i].expr is { } expr) { - _linearExpression = (_linearExpression == null ? _candidateColumns[i].expr : new BinaryNode(_table, Operators.And, _candidateColumns[i].expr, _linearExpression)); + _linearExpression = (_linearExpression == null ? _candidateColumns[i].expr : new BinaryNode(_table, Operators.And, expr, _linearExpression)); } } else @@ -499,6 +509,7 @@ namespace System.Data bool needSorting = true; InitCandidateColumns(); + Debug.Assert(_candidateColumns != null); if (_expression is BinaryNode) { @@ -539,7 +550,7 @@ namespace System.Data needSorting = false; } - if (_index.RecordCount == 0) + if (_index!.RecordCount == 0) return _table.NewRowArray(0); Range range; @@ -580,14 +591,14 @@ namespace System.Data DataRow[] newRows = _table.NewRowArray(_recordCount); for (int i = 0; i < newRows.Length; i++) { - newRows[i] = _table._recordManager[_records[i]]; + newRows[i] = _table._recordManager[_records![i]]!; } return newRows; } private bool AcceptRecord(int record) { - DataRow row = _table._recordManager[record]; + DataRow? row = _table._recordManager[record]; if (row == null) return true; @@ -606,7 +617,7 @@ namespace System.Data version = DataRowVersion.Proposed; } - object val = _linearExpression.Eval(row, version); + object val = _linearExpression!.Eval(row, version); bool result; try { @@ -614,7 +625,7 @@ namespace System.Data } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { - throw ExprException.FilterConvertion(_rowFilter.Expression); + throw ExprException.FilterConvertion(_rowFilter!.Expression); } return result; } @@ -673,10 +684,10 @@ namespace System.Data // use InvariantCulture instead of DataTable.Locale because in the Danish related cultures // sorting a Guid as a string has different results than in Invariant and English related cultures. // This fix is restricted to DataTable.Select("GuidColumn = 'string literal'") types of queries - NameNode namedNode = null; - System.Globalization.CompareInfo comparer = - ((isLConst && !isRConst && (leftType == StorageType.String) && (rightType == StorageType.Guid) && (null != (namedNode = expr._right as NameNode)) && (namedNode._column.DataType == typeof(Guid))) || - (isRConst && !isLConst && (rightType == StorageType.String) && (leftType == StorageType.Guid) && (null != (namedNode = expr._left as NameNode)) && (namedNode._column.DataType == typeof(Guid)))) + NameNode? namedNode = null; + System.Globalization.CompareInfo? comparer = + ((isLConst && !isRConst && (leftType == StorageType.String) && (rightType == StorageType.Guid) && (null != (namedNode = expr._right as NameNode)) && (namedNode._column!.DataType == typeof(Guid))) || + (isRConst && !isLConst && (rightType == StorageType.String) && (leftType == StorageType.Guid) && (null != (namedNode = expr._left as NameNode)) && (namedNode._column!.DataType == typeof(Guid)))) ? System.Globalization.CultureInfo.InvariantCulture.CompareInfo : null; c = expr.BinaryCompare(vLeft, vRight, resultType, expr._op, comparer); @@ -697,7 +708,9 @@ namespace System.Data private int Evaluate(int record) { - DataRow row = _table._recordManager[record]; + Debug.Assert(_index != null && _candidateColumns != null); + + DataRow? row = _table._recordManager[record]; if (row == null) return 0; @@ -719,10 +732,10 @@ namespace System.Data IndexField[] fields = _index._indexFields; for (int i = 0; i < _matchedCandidates; i++) { - int columnOrdinal = fields[i].Column.Ordinal; - Debug.Assert(_candidateColumns[columnOrdinal] != null, "How come this is not a candidate column"); - Debug.Assert(_candidateColumns[columnOrdinal].expr != null, "How come there is no associated expression"); - int c = Eval(_candidateColumns[columnOrdinal].expr, row, version); + var candidateColumn = _candidateColumns[fields[i].Column.Ordinal]; + Debug.Assert(candidateColumn != null, "How come this is not a candidate column"); + Debug.Assert(candidateColumn.expr != null, "How come there is no associated expression"); + int c = Eval(candidateColumn.expr, row, version); if (c != 0) return fields[i].IsDescending ? -c : c; } @@ -731,6 +744,8 @@ namespace System.Data private int FindFirstMatchingRecord() { + Debug.Assert(_index != null); + int rec = -1; int lo = 0; int hi = _index.RecordCount - 1; @@ -748,6 +763,8 @@ namespace System.Data private int FindLastMatchingRecord(int lo) { + Debug.Assert(_index != null); + int rec = -1; int hi = _index.RecordCount - 1; while (lo <= hi) @@ -764,6 +781,8 @@ namespace System.Data private Range GetBinaryFilteredRecords() { + Debug.Assert(_index != null); + if (_matchedCandidates == 0) { return new Range(0, _index.RecordCount - 1); @@ -781,6 +800,8 @@ namespace System.Data private int[] GetLinearFilteredRecords(Range range) { + Debug.Assert(_index != null); + if (_linearExpression == null) { int[] resultRecords = new int[range.Count]; @@ -808,6 +829,8 @@ namespace System.Data private DataRow[] GetLinearFilteredRows(Range range) { + Debug.Assert(_index != null); + DataRow[] resultRows; if (_linearExpression == null) { @@ -820,7 +843,7 @@ namespace System.Data { if (AcceptRecord(iterator.Current)) { - matchingRows.Add(_table._recordManager[iterator.Current]); + matchingRows.Add(_table._recordManager[iterator.Current]!); } } resultRows = _table.NewRowArray(matchingRows.Count); @@ -842,16 +865,17 @@ namespace System.Data } } - long id1 = _table._recordManager[record1] == null ? 0 : _table._recordManager[record1].rowID; - long id2 = _table._recordManager[record2] == null ? 0 : _table._recordManager[record2].rowID; + var (row1, row2) = (_table._recordManager[record1], _table._recordManager[record2]); + + long id1 = row1 is null ? 0 : row1.rowID; + long id2 = row2 is null ? 0 : row2.rowID; int diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0); // if they're two records in the same row, we need to be able to distinguish them. - if (diff == 0 && record1 != record2 && - _table._recordManager[record1] != null && _table._recordManager[record2] != null) + if (diff == 0 && record1 != record2 && row1 != null && row2 != null) { - id1 = (int)_table._recordManager[record1].GetRecordState(record1); - id2 = (int)_table._recordManager[record2].GetRecordState(record2); + id1 = (int)row1.GetRecordState(record1); + id2 = (int)row2.GetRecordState(record2); diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0); } @@ -866,7 +890,7 @@ namespace System.Data { i = left; j = right; - record = _records[i + j >> 1]; + record = _records![i + j >> 1]; do { while (CompareRecords(_records[i], record) < 0) i++; diff --git a/src/libraries/System.Data.Common/src/System/Data/Selection.cs b/src/libraries/System.Data.Common/src/System/Data/Selection.cs index c09ede7..c66dc5b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Selection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Selection.cs @@ -27,7 +27,7 @@ namespace System.Data public static bool operator !=(IndexField if1, IndexField if2) => !(if1 == if2); // must override Equals if == operator is defined - public override bool Equals(object obj) => obj is IndexField ? + public override bool Equals(object? obj) => obj is IndexField ? this == (IndexField)obj : false; @@ -64,11 +64,11 @@ namespace System.Data /// Allow a user implemented comparison of two DataRow /// User must use correct DataRowVersion in comparison or index corruption will happen - private readonly System.Comparison _comparison; + private readonly System.Comparison? _comparison; private readonly DataViewRowState _recordStates; - private readonly WeakReference _rowFilter; - private IndexTree _records; + private readonly WeakReference? _rowFilter; + private IndexTree _records = null!; // Always initialized in InitRecords private int _recordCount; private int _refCount; @@ -84,12 +84,12 @@ namespace System.Data private static int s_objectTypeCount; // Bid counter private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount); - public Index(DataTable table, IndexField[] indexFields, DataViewRowState recordStates, IFilter rowFilter) : + public Index(DataTable table, IndexField[] indexFields, DataViewRowState recordStates, IFilter? rowFilter) : this(table, indexFields, null, recordStates, rowFilter) { } - public Index(DataTable table, System.Comparison comparison, DataViewRowState recordStates, IFilter rowFilter) : + public Index(DataTable table, System.Comparison comparison, DataViewRowState recordStates, IFilter? rowFilter) : this(table, GetAllFields(table.Columns), comparison, recordStates, rowFilter) { } @@ -105,7 +105,7 @@ namespace System.Data return fields; } - private Index(DataTable table, IndexField[] indexFields, System.Comparison comparison, DataViewRowState recordStates, IFilter rowFilter) + private Index(DataTable table, IndexField[] indexFields, System.Comparison? comparison, DataViewRowState recordStates, IFilter? rowFilter) { DataCommonEventSource.Log.Trace(" {0}, table={1}, recordStates={2}", ObjectID, (table != null) ? table.ObjectID : 0, recordStates); @@ -127,7 +127,7 @@ namespace System.Data if (null != rowFilter) { _rowFilter = new WeakReference(rowFilter); - DataExpression expr = (rowFilter as DataExpression); + DataExpression? expr = (rowFilter as DataExpression); if (null != expr) { _hasRemoteAggregate = expr.HasRemoteAggregate(); @@ -139,7 +139,7 @@ namespace System.Data // if caller does not AddRef, it is expected to be a one-time read operation because the index won't be maintained on writes } - public bool Equal(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) + public bool Equal(IndexField[] indexDesc, DataViewRowState recordStates, IFilter? rowFilter) { if (!_isSharable || _indexFields.Length != indexDesc.Length || @@ -167,7 +167,7 @@ namespace System.Data public DataViewRowState RecordStates => _recordStates; - public IFilter RowFilter => (IFilter)((null != _rowFilter) ? _rowFilter.Target : null); + public IFilter? RowFilter => (IFilter?)((null != _rowFilter) ? _rowFilter.Target : null); public int GetRecord(int recordIndex) { @@ -183,7 +183,7 @@ namespace System.Data private bool AcceptRecord(int record) => AcceptRecord(record, RowFilter); - private bool AcceptRecord(int record, IFilter filter) + private bool AcceptRecord(int record, IFilter? filter) { DataCommonEventSource.Log.Trace(" {0}, record={1}", ObjectID, record); if (filter == null) @@ -191,7 +191,7 @@ namespace System.Data return true; } - DataRow row = _table._recordManager[record]; + DataRow? row = _table._recordManager[record]; if (row == null) { @@ -320,12 +320,14 @@ namespace System.Data } else { - Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); - Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); + var (row1, row2) = (_table._recordManager[record1], _table._recordManager[record2]); + + Debug.Assert(null != row1, "record1 no datarow"); + Debug.Assert(null != row2, "record2 no datarow"); // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. - return _table.Rows.IndexOf(_table._recordManager[record1]).CompareTo(_table.Rows.IndexOf(_table._recordManager[record2])); + return _table.Rows.IndexOf(row1).CompareTo(_table.Rows.IndexOf(row2)); } } @@ -333,7 +335,7 @@ namespace System.Data { _table._recordManager.VerifyRecord(record1, _table._recordManager[record1]); _table._recordManager.VerifyRecord(record2, _table._recordManager[record2]); - return _comparison(_table._recordManager[record1], _table._recordManager[record2]); + return _comparison!(_table._recordManager[record1], _table._recordManager[record2]); } @@ -355,31 +357,32 @@ namespace System.Data } } #endif - Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); - Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); + var (row1, row2) = (_table._recordManager[record1], _table._recordManager[record2]); + Debug.Assert(null != row1, "record1 no datarow"); + Debug.Assert(null != row2, "record2 no datarow"); - if (null == _table._recordManager[record1]) + if (null == row1) { - return ((null == _table._recordManager[record2]) ? 0 : -1); + return ((null == row2) ? 0 : -1); } - else if (null == _table._recordManager[record2]) + else if (null == row2) { return 1; } // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. - int diff = _table._recordManager[record1].rowID.CompareTo(_table._recordManager[record2].rowID); + int diff = row1.rowID.CompareTo(row2.rowID); // if they're two records in the same row, we need to be able to distinguish them. if ((diff == 0) && (record1 != record2)) { - diff = ((int)_table._recordManager[record1].GetRecordState(record1)).CompareTo((int)_table._recordManager[record2].GetRecordState(record2)); + diff = ((int)row1.GetRecordState(record1)).CompareTo((int)row2.GetRecordState(record2)); } return diff; } - private int CompareRecordToKey(int record1, object[] vals) + private int CompareRecordToKey(int record1, object?[] vals) { for (int i = 0; i < _indexFields.Length; i++) { @@ -444,7 +447,7 @@ namespace System.Data Debug.Assert(null != _comparison, "missing comparison"); int index; - DataRow row = _table._recordManager[record]; + DataRow row = _table._recordManager[record]!; int a = row._newRecord; int b = row._oldRecord; @@ -509,7 +512,7 @@ namespace System.Data return -1; } - public int FindRecordByKey(object key) + public int FindRecordByKey(object? key) { int nodeId = FindNodeByKey(key); if (IndexTree.NIL != nodeId) @@ -519,7 +522,7 @@ namespace System.Data return -1; // return -1 to user indicating record not found } - public int FindRecordByKey(object[] key) + public int FindRecordByKey(object?[] key) { int nodeId = FindNodeByKeys(key); if (IndexTree.NIL != nodeId) @@ -529,7 +532,7 @@ namespace System.Data return -1; // return -1 to user indicating record not found } - private int FindNodeByKey(object originalKey) + private int FindNodeByKey(object? originalKey) { int x, c; if (_indexFields.Length != 1) @@ -542,7 +545,7 @@ namespace System.Data { // otherwise storage may not exist DataColumn column = _indexFields[0].Column; - object key = column.ConvertValue(originalKey); + object? key = column.ConvertValue(originalKey); x = _records.root; if (_indexFields[0].IsDescending) @@ -569,11 +572,11 @@ namespace System.Data return x; } - private int FindNodeByKeys(object[] originalKey) + private int FindNodeByKeys(object?[]? originalKey) { int x, c; c = ((null != originalKey) ? originalKey.Length : 0); - if ((0 == c) || (_indexFields.Length != c)) + if (originalKey is null || 0 == c || _indexFields.Length != c) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, c); } @@ -583,7 +586,7 @@ namespace System.Data { // otherwise storage may not exist // copy array to avoid changing original - object[] key = new object[originalKey.Length]; + object?[] key = new object?[originalKey.Length]; for (int i = 0; i < originalKey.Length; ++i) { key[i] = _indexFields[i].Column.ConvertValue(originalKey[i]); @@ -628,7 +631,7 @@ namespace System.Data int x = _records.root; while (IndexTree.NIL != x) { - int c = comparison(key, (TRow)_table._recordManager[_records.Key(x)]); + int c = comparison(key, (TRow)_table._recordManager[_records.Key(x)]!); if (c == 0) { break; } if (c < 0) { x = _records.Left(x); } else { x = _records.Right(x); } @@ -654,13 +657,13 @@ namespace System.Data return new Range(recordIndex, recordIndex + span - 1); } - public Range FindRecords(object key) + public Range FindRecords(object? key) { int nodeId = FindNodeByKey(key); // main tree node associated with key return GetRangeFromNode(nodeId); } - public Range FindRecords(object[] key) + public Range FindRecords(object?[] key) { int nodeId = FindNodeByKeys(key); // main tree node associated with key return GetRangeFromNode(nodeId); @@ -708,7 +711,7 @@ namespace System.Data return newRows; } - private void InitRecords(IFilter filter) + private void InitRecords(IFilter? filter) { DataViewRowState states = _recordStates; @@ -866,7 +869,7 @@ namespace System.Data Debug.Assert(-1 <= record, "bad record#"); _listeners.Notify(changedType, ((0 <= record) ? _table._recordManager[record] : null), trackAddRemove, - delegate (DataViewListener listener, ListChangedType type, DataRow row, bool track) + delegate (DataViewListener listener, ListChangedType type, DataRow? row, bool track) { listener.MaintainDataView(changedType, row, track); }); @@ -1019,7 +1022,7 @@ namespace System.Data } } - internal static int IndexOfReference(List list, T item) where T : class + internal static int IndexOfReference(List? list, T item) where T : class { if (null != list) { @@ -1033,7 +1036,7 @@ namespace System.Data } return -1; } - internal static bool ContainsReference(List list, T item) where T : class + internal static bool ContainsReference(List list, T item) where T : class { return (0 <= IndexOfReference(list, item)); } @@ -1041,8 +1044,8 @@ namespace System.Data internal sealed class Listeners where TElem : class { - private readonly List _listeners; - private readonly Func _filter; + private readonly List _listeners; + private readonly Func _filter; private readonly int _objectID; private int _listenerReaderCount; @@ -1052,9 +1055,9 @@ namespace System.Data /// Wish this was defined in mscorlib.dll instead of System.Core.dll internal delegate TResult Func(T1 arg1); - internal Listeners(int ObjectID, Func notifyFilter) + internal Listeners(int ObjectID, Func notifyFilter) { - _listeners = new List(); + _listeners = new List(); _filter = notifyFilter; _objectID = ObjectID; _listenerReaderCount = 0; @@ -1112,12 +1115,12 @@ namespace System.Data for (int i = 0; i < count; ++i) { // protect against listener being set to null (instead of being removed) - TElem listener = _listeners[i]; + TElem? listener = _listeners[i]; if (_filter(listener)) { // perform the action on each listener // some actions may throw an exception blocking remaning listeners from being notified (just like events) - action(listener, arg1, arg2, arg3); + action(listener!, arg1, arg2, arg3); } else { diff --git a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs index 79d21e8..c239328 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs @@ -12,10 +12,10 @@ namespace System.Data { internal sealed class SimpleType : ISerializable { - private string _baseType; // base type name - private SimpleType _baseSimpleType; - private XmlQualifiedName _xmlBaseType; // Qualified name of Basetype - private string _name = string.Empty; + private string? _baseType; // base type name + private SimpleType? _baseSimpleType; + private XmlQualifiedName? _xmlBaseType; // Qualified name of Basetype + private string? _name = string.Empty; private int _length = -1; private int _minLength = -1; private int _maxLength = -1; @@ -57,10 +57,10 @@ namespace System.Data { XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction)node.Content; - XmlSchemaSimpleType ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType; + XmlSchemaSimpleType? ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType; if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) { - _baseSimpleType = new SimpleType(node.BaseXmlSchemaType as XmlSchemaSimpleType); + _baseSimpleType = new SimpleType(ancestor); } // do we need to put qualified name? @@ -143,7 +143,7 @@ namespace System.Data ); } - internal string BaseType + internal string? BaseType { get { @@ -151,7 +151,7 @@ namespace System.Data } } - internal XmlQualifiedName XmlBaseType + internal XmlQualifiedName? XmlBaseType { get { @@ -159,7 +159,7 @@ namespace System.Data } } - internal string Name + internal string? Name { get { @@ -195,7 +195,7 @@ namespace System.Data } } - internal SimpleType BaseSimpleType + internal SimpleType? BaseSimpleType { get { @@ -203,7 +203,7 @@ namespace System.Data } } // return qualified name of this simple type - public string SimpleTypeQualifiedName + public string? SimpleTypeQualifiedName { get { @@ -248,7 +248,7 @@ namespace System.Data { if (_baseSimpleType.Namespace != null && _baseSimpleType.Namespace.Length > 0) { - string prefix = (prefixes != null) ? (string)prefixes[_baseSimpleType.Namespace] : null; + string? prefix = (prefixes != null) ? (string?)prefixes[_baseSimpleType.Namespace] : null; if (prefix != null) { type.SetAttribute(Keywords.BASE, (prefix + ":" + _baseSimpleType.Name)); @@ -265,12 +265,12 @@ namespace System.Data } else { - type.SetAttribute(Keywords.BASE, QualifiedName(_baseType)); // has to be xs:SomePrimitiveType + type.SetAttribute(Keywords.BASE, QualifiedName(_baseType!)); // has to be xs:SomePrimitiveType } } else { - type.SetAttribute(Keywords.BASE, (_baseSimpleType != null) ? _baseSimpleType.Name : QualifiedName(_baseType)); + type.SetAttribute(Keywords.BASE, (_baseSimpleType != null) ? _baseSimpleType.Name : QualifiedName(_baseType!)); } XmlElement constraint; @@ -311,7 +311,7 @@ namespace System.Data return limitedString; } - internal static SimpleType CreateSimpleType(StorageType typeCode, Type type) + internal static SimpleType? CreateSimpleType(StorageType typeCode, Type type) { if ((typeCode == StorageType.Char) && (type == typeof(char))) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs index 234b7f5..2889e24 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SortExpressionBuilder.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -40,8 +41,8 @@ namespace System.Data private readonly LinkedList> _selectors = new LinkedList>(); private readonly LinkedList> _comparers = new LinkedList>(); - private LinkedListNode> _currentSelector; - private LinkedListNode> _currentComparer; + private LinkedListNode>? _currentSelector; + private LinkedListNode>? _currentComparer; /// /// Adds a sorting selector/comparer in the correct order @@ -91,9 +92,9 @@ namespace System.Data /// Note: Comparison is done in the order it was Added. /// /// Comparison result of the combined Sort comparer expression - public int Compare(List a, List b) + public int Compare([AllowNull] List a, [AllowNull] List b) { - Debug.Assert(a.Count == Count); + Debug.Assert(a != null && b != null && a.Count == Count); int i = 0; foreach (Comparison compare in _comparers) @@ -130,7 +131,7 @@ namespace System.Data foreach (Func selector in _selectors) { - if (selector == _currentSelector.Value) + if (selector == _currentSelector!.Value) { builder._currentSelector = builder._selectors.AddLast(selector); } @@ -143,7 +144,7 @@ namespace System.Data foreach (Comparison comparer in _comparers) { - if (comparer == _currentComparer.Value) + if (comparer == _currentComparer!.Value) { builder._currentComparer = builder._comparers.AddLast(comparer); } @@ -165,20 +166,20 @@ namespace System.Data foreach (Func selector in _selectors) { - if (selector == _currentSelector.Value) + if (selector == _currentSelector!.Value) { - builder._currentSelector = builder._selectors.AddLast(r => selector((T)(object)r)); + builder._currentSelector = builder._selectors.AddLast(r => selector((T)(object)r!)); } else { - builder._selectors.AddLast(r => selector((T)(object)r)); + builder._selectors.AddLast(r => selector((T)(object)r!)); } } foreach (Comparison comparer in _comparers) { - if (comparer == _currentComparer.Value) + if (comparer == _currentComparer!.Value) { builder._currentComparer = builder._comparers.AddLast(comparer); } @@ -190,6 +191,5 @@ namespace System.Data return builder; } - } } diff --git a/src/libraries/System.Data.Common/src/System/Data/StateChangeEvent.cs b/src/libraries/System.Data.Common/src/System/Data/StateChangeEvent.cs index 53016bf..a275c9e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/StateChangeEvent.cs +++ b/src/libraries/System.Data.Common/src/System/Data/StateChangeEvent.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data { public sealed class StateChangeEventArgs : EventArgs diff --git a/src/libraries/System.Data.Common/src/System/Data/StateChangeEventHandler.cs b/src/libraries/System.Data.Common/src/System/Data/StateChangeEventHandler.cs index 80d7158..d4a33ad 100644 --- a/src/libraries/System.Data.Common/src/System/Data/StateChangeEventHandler.cs +++ b/src/libraries/System.Data.Common/src/System/Data/StateChangeEventHandler.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace System.Data { public delegate void StateChangeEventHandler(object sender, StateChangeEventArgs e); diff --git a/src/libraries/System.Data.Common/src/System/Data/StrongTypingException.cs b/src/libraries/System.Data.Common/src/System/Data/StrongTypingException.cs index a900eea..f170174 100644 --- a/src/libraries/System.Data.Common/src/System/Data/StrongTypingException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/StrongTypingException.cs @@ -22,12 +22,12 @@ namespace System.Data HResult = HResults.StrongTyping; } - public StrongTypingException(string message) : base(message) + public StrongTypingException(string? message) : base(message) { HResult = HResults.StrongTyping; } - public StrongTypingException(string s, Exception innerException) : base(s, innerException) + public StrongTypingException(string? s, Exception? innerException) : base(s, innerException) { HResult = HResults.StrongTyping; } diff --git a/src/libraries/System.Data.Common/src/System/Data/TypedTableBaseExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/TypedTableBaseExtensions.cs index eb6fbcc..9153511 100644 --- a/src/libraries/System.Data.Common/src/System/Data/TypedTableBaseExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/TypedTableBaseExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Data { @@ -91,6 +92,7 @@ namespace System.Data return new EnumerableRowCollection(source as DataTable); } + [return: MaybeNull] public static TRow ElementAtOrDefault(this TypedTableBase source, int index) where TRow : DataRow { if ((index >= 0) && (index < source.Rows.Count)) diff --git a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs index efe3475..f151257 100644 --- a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs @@ -13,18 +13,18 @@ namespace System.Data public class UniqueConstraint : Constraint { private DataKey _key; - private Index _constraintIndex; + private Index? _constraintIndex; internal bool _bPrimaryKey; // Design time serialization - internal string _constraintName; - internal string[] _columnNames; + internal string? _constraintName; + internal string[]? _columnNames; /// /// Initializes a new instance of the with the specified name and /// . /// - public UniqueConstraint(string name, DataColumn column) + public UniqueConstraint(string? name, DataColumn column) { DataColumn[] columns = new DataColumn[1]; columns[0] = column; @@ -45,7 +45,7 @@ namespace System.Data /// Initializes a new instance of the with the specified name and array /// of objects. /// - public UniqueConstraint(string name, DataColumn[] columns) + public UniqueConstraint(string? name, DataColumn[] columns) { Create(name, columns); } @@ -61,7 +61,7 @@ namespace System.Data // Construct design time object [Browsable(false)] - public UniqueConstraint(string name, string[] columnNames, bool isPrimaryKey) + public UniqueConstraint(string? name, string[]? columnNames, bool isPrimaryKey) { _constraintName = name; _columnNames = columnNames; @@ -72,7 +72,7 @@ namespace System.Data /// Initializes a new instance of the with the specified name and /// . /// - public UniqueConstraint(string name, DataColumn column, bool isPrimaryKey) + public UniqueConstraint(string? name, DataColumn column, bool isPrimaryKey) { DataColumn[] columns = new DataColumn[1]; columns[0] = column; @@ -95,7 +95,7 @@ namespace System.Data /// Initializes a new instance of the with the specified name and array /// of objects. /// - public UniqueConstraint(string name, DataColumn[] columns, bool isPrimaryKey) + public UniqueConstraint(string? name, DataColumn[] columns, bool isPrimaryKey) { _bPrimaryKey = isPrimaryKey; Create(name, columns); @@ -126,7 +126,7 @@ namespace System.Data get { AssertConstraintAndKeyIndexes(); - return _constraintIndex; + return _constraintIndex!; } } @@ -189,7 +189,7 @@ namespace System.Data else throw ExceptionBuilder.RemovePrimaryKey(constraints.Table); } - for (ParentForeignKeyConstraintEnumerator cs = new ParentForeignKeyConstraintEnumerator(Table.DataSet, Table); cs.GetNext();) + for (ParentForeignKeyConstraintEnumerator cs = new ParentForeignKeyConstraintEnumerator(Table!.DataSet, Table); cs.GetNext();) { ForeignKeyConstraint constraint = cs.GetForeignKeyConstraint(); if (!_key.ColumnsEqual(constraint.ParentKey)) @@ -206,7 +206,7 @@ namespace System.Data internal override bool CanEnableConstraint() { - if (Table.EnforceConstraints) + if (Table!.EnforceConstraints) return ConstraintIndex.CheckUnique(); return true; @@ -244,7 +244,7 @@ namespace System.Data internal override void CheckConstraint(DataRow row, DataRowAction action) { - if (Table.EnforceConstraints && + if (Table!.EnforceConstraints && (action == DataRowAction.Add || action == DataRowAction.Change || (action == DataRowAction.Rollback && row._tempRecord != -1))) @@ -265,21 +265,21 @@ namespace System.Data return _key.ContainsColumn(column); } - internal override Constraint Clone(DataSet destination) + internal override Constraint? Clone(DataSet destination) { return Clone(destination, false); } - internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup) + internal override Constraint? Clone(DataSet destination, bool ignorNSforTableLookup) { int iDest; if (ignorNSforTableLookup) { - iDest = destination.Tables.IndexOf(Table.TableName); + iDest = destination.Tables.IndexOf(Table!.TableName); } else { - iDest = destination.Tables.IndexOf(Table.TableName, Table.Namespace, false); // pass false for last param to be backward compatable + iDest = destination.Tables.IndexOf(Table!.TableName, Table.Namespace, false); // pass false for last param to be backward compatable } if (iDest < 0) @@ -309,7 +309,7 @@ namespace System.Data return clone; } - internal UniqueConstraint Clone(DataTable table) + internal UniqueConstraint? Clone(DataTable table) { int keys = ColumnsReference.Length; DataColumn[] columns = new DataColumn[keys]; @@ -369,7 +369,7 @@ namespace System.Data } } - private void Create(string constraintName, DataColumn[] columns) + private void Create(string? constraintName, DataColumn[] columns) { for (int i = 0; i < columns.Length; i++) { @@ -386,7 +386,7 @@ namespace System.Data /// /// Compares this constraint to a second to determine if both are identical. /// - public override bool Equals(object key2) + public override bool Equals(object? key2) { if (!(key2 is UniqueConstraint)) return false; @@ -423,7 +423,7 @@ namespace System.Data /// Gets the table to which this constraint belongs. /// [ReadOnly(true)] - public override DataTable Table + public override DataTable? Table { get { diff --git a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs index 7959f61..7885dc7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Xml; using System.Collections; using System.Globalization; diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs index 7082321..39e1eed 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Diagnostics; using System.Collections; using System.Xml; diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index 192efd2..634b96e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Data.Common; using System.Xml; using System.Xml.Schema; @@ -689,7 +692,7 @@ namespace System.Data { if (dc.SimpleType != null && dc.SimpleType.Name != null && dc.SimpleType.Name.Length != 0) { - _existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName] = dc; + _existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName!] = dc; // existingSimpleTypeMap[dc.SimpleType.SimpleTypeQualifiedName] = dc.SimpleType; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs index 6eaf2d6..1453fe8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Collections; using System.Collections.Generic; using System.Data.Common; diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs index 0b1295f..f74bf37 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Xml; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index 08af62a..959cebb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -27,42 +27,42 @@ namespace System.Data /// internal sealed class XmlTreeGen { - private ArrayList _constraintNames; - private Hashtable _namespaces; - private Hashtable _autogenerated; - private Hashtable _prefixes; + private ArrayList? _constraintNames; + private Hashtable? _namespaces; + private Hashtable _autogenerated = default!; // Late-initialized + private Hashtable? _prefixes; - private DataSet _ds; + private DataSet? _ds; private readonly ArrayList _tables = new ArrayList(); private readonly ArrayList _relations = new ArrayList(); - private XmlDocument _dc; - private XmlElement _sRoot; + private XmlDocument? _dc; + private XmlElement? _sRoot; private int _prefixCount; private readonly SchemaFormat _schFormat = SchemaFormat.Public; - private string _filePath; - private string _fileName; - private string _fileExt; - private XmlElement _dsElement; - private XmlElement _constraintSeparator; + private string? _filePath; + private string? _fileName; + private string? _fileExt; + private XmlElement? _dsElement; + private XmlElement? _constraintSeparator; /// /// This converter allows new versions of the framework to write /// the assembly version of older versions of the framework. /// - private Converter _targetConverter; + private Converter? _targetConverter; internal XmlTreeGen(SchemaFormat format) { _schFormat = format; } - internal static void AddExtendedProperties(PropertyCollection props, XmlElement node) + internal static void AddExtendedProperties(PropertyCollection? props, XmlElement node) { AddExtendedProperties(props, node, null); } - internal static void AddExtendedProperties(PropertyCollection props, XmlElement node, Type type) + internal static void AddExtendedProperties(PropertyCollection? props, XmlElement node, Type? type) { if (props != null) { @@ -76,7 +76,7 @@ namespace System.Data } else { - s = Convert.ToString(entry.Key, CultureInfo.InvariantCulture); + s = Convert.ToString(entry.Key, CultureInfo.InvariantCulture)!; } if (entry.Value is INullable) @@ -89,7 +89,7 @@ namespace System.Data } else { - v = Convert.ToString(entry.Value, CultureInfo.InvariantCulture); + v = Convert.ToString(entry.Value, CultureInfo.InvariantCulture)!; } if (type == typeof(DataRelation)) @@ -105,7 +105,7 @@ namespace System.Data } } - internal void AddXdoProperties(object instance, XmlElement root, XmlDocument xd) + internal void AddXdoProperties(object? instance, XmlElement root, XmlDocument xd) { if (instance == null) { @@ -130,7 +130,7 @@ namespace System.Data { Type type = pd.PropertyType; bool bisDataColumn = false; - DataColumn col = null; // it may cause problem to assign null here, I will need to change this. + DataColumn? col = null; // it may cause problem to assign null here, I will need to change this. bool bIsSqlType = false; bool bImplementsInullable = false; @@ -192,7 +192,7 @@ namespace System.Data { if (string.Equals(pd.Name, "DataType", StringComparison.Ordinal)) { - string dt = XmlDataTypeName(col.DataType); + string dt = XmlDataTypeName(col!.DataType); if (bIsSqlType || (col.DataType == typeof(System.Numerics.BigInteger))) { root.SetAttribute(Keywords.MSD_DATATYPE, Keywords.MSDNS, col.DataType.FullName); @@ -275,7 +275,7 @@ namespace System.Data private void GenerateConstraintNames(DataTable table, bool fromTable) { // if constraint created obased on relation and it is self related rel. then add constraint - StringBuilder builder = null; + StringBuilder? builder = null; foreach (Constraint constr in table.Constraints) { if (fromTable) @@ -291,7 +291,7 @@ namespace System.Data int nameInt = 0; string name = constr.ConstraintName; - while (_constraintNames.Contains(name)) + while (_constraintNames!.Contains(name)) { if (null == builder) { @@ -316,7 +316,7 @@ namespace System.Data { for (int i = 0; i < tables.Count; i++) { - GenerateConstraintNames((DataTable)tables[i], true); + GenerateConstraintNames((DataTable)tables[i]!, true); } } @@ -329,7 +329,7 @@ namespace System.Data } //Does the DS or ANY object in it have ExtendedProperties? - private static bool _PropsNotEmpty(PropertyCollection props) + private static bool _PropsNotEmpty(PropertyCollection? props) { return props != null && props.Count != 0; } @@ -417,7 +417,7 @@ namespace System.Data { for (int i = 0; i < dt.Count; i++) { - SetupAutoGenerated((DataTable)dt[i]); + SetupAutoGenerated((DataTable)dt[i]!); } } @@ -431,7 +431,7 @@ namespace System.Data foreach (Constraint cs in dt.Constraints) { - ForeignKeyConstraint fk = (cs as ForeignKeyConstraint); + ForeignKeyConstraint? fk = (cs as ForeignKeyConstraint); if (null != fk) { if (AutoGenerated(fk)) @@ -443,7 +443,7 @@ namespace System.Data if (_autogenerated[fk.RelatedColumnsReference[0]] != null) _autogenerated[fk.RelatedColumnsReference[0]] = null; // special case of the ghosted constraints: - UniqueConstraint _constraint = (UniqueConstraint)fk.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fk.RelatedColumnsReference)); + UniqueConstraint? _constraint = (UniqueConstraint?)fk.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fk.RelatedColumnsReference)); if (_constraint == null) continue; @@ -499,7 +499,7 @@ namespace System.Data ArrayList topTables = new ArrayList(); for (int i = 0; i < _tables.Count; i++) { - DataTable table = (DataTable)_tables[i]; + DataTable table = (DataTable)_tables[i]!; if (table.ParentRelations.Count == 0) topTables.Add(table); else @@ -533,7 +533,7 @@ namespace System.Data // SxS: this method can generate XSD files if the input xmlWriter is XmlTextWriter or DataTextWriter and its underlying stream is FileStream // These XSDs are located in the same folder as the underlying stream's file path (see SetPath method). - internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet ds, DataTable dt, bool writeHierarchy) + internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataTable? dt, bool writeHierarchy) { _constraintNames = new ArrayList(); _autogenerated = new Hashtable(); @@ -544,7 +544,7 @@ namespace System.Data DataTable[] top; bool fFlat = false; - DataTable _dt = dt; + DataTable _dt = dt!; if (ds != null) { @@ -556,7 +556,7 @@ namespace System.Data } else { - if (dt.DataSet != null) + if (dt!.DataSet != null) { // preserve datatable's dataset to use for xml // if null it would write out document element instead of dt.DataSet.DataSetName @@ -658,7 +658,7 @@ namespace System.Data FillDataSetElement(xd, ds, dt); rootSchema.AppendChild(_dsElement); AddXdoProperties(_ds, _dsElement, xd); - AddExtendedProperties(ds._extendedProperties, _dsElement); + AddExtendedProperties(ds!._extendedProperties, _dsElement); xd.AppendChild(rootSchema); @@ -730,7 +730,7 @@ namespace System.Data if ((_ds != null && _ds.Namespace == top[i].Namespace) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting)) node.SetAttribute(Keywords.REF, top[i].EncodedTableName); else - node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]) + ':' + top[i].EncodedTableName); + node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]!) + ':' + top[i].EncodedTableName); dsCompositor.AppendChild(node); } @@ -741,7 +741,7 @@ namespace System.Data { AppendChildWithoutRef(rootSchema, top[i].Namespace, el, Keywords.XSD_ELEMENT); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); - node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]) + ':' + top[i].EncodedTableName); + node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]!) + ':' + top[i].EncodedTableName); dsCompositor.AppendChild(node); } } @@ -763,13 +763,13 @@ namespace System.Data } else if (writeHierarchy && _tables.Count > 0) { - CreateRelations((DataTable)_tables[0]); + CreateRelations((DataTable)_tables[0]!); rels = new DataRelation[_relations.Count]; _relations.CopyTo(rels, 0); } - XmlElement nodeAnn = null; - XmlElement nodeApp = null; + XmlElement? nodeAnn = null; + XmlElement? nodeApp = null; for (int i = 0; i < rels.Length; ++i) { @@ -794,7 +794,7 @@ namespace System.Data } - XmlComment comment = null; + XmlComment? comment = null; bool isMultipleNamespaceAndStreamingWriter = (_namespaces.Count > 1 && !genSecondary); if (_schFormat != SchemaFormat.Remoting && _schFormat != SchemaFormat.RemotingSkipSchema) @@ -838,7 +838,7 @@ namespace System.Data continue; } - XmlWriter xw = null; + XmlWriter? xw = null; if (!genSecondary) { @@ -860,7 +860,7 @@ namespace System.Data xw.WriteStartDocument(true); } - XmlElement tNode = (XmlElement)_namespaces[ns]; + XmlElement tNode = (XmlElement)_namespaces[ns]!; _dc.AppendChild(tNode); foreach (string imp_ns in _namespaces.Keys) @@ -869,7 +869,7 @@ namespace System.Data { continue; // don't write out yourself } - string prefix = (string)_prefixes[imp_ns]; + string? prefix = (string?)_prefixes[imp_ns]; if (prefix == null) { // only for dataset.Namespace == empty continue; // do nothing @@ -1002,15 +1002,18 @@ namespace System.Data return rootSchema; } - internal XmlElement FillDataSetElement(XmlDocument xd, DataSet ds, DataTable dt) + internal XmlElement FillDataSetElement(XmlDocument xd, DataSet? ds, DataTable? dt) { - DataSet dataSet = (ds != null) ? ds : dt.DataSet; + Debug.Assert(ds == null || dt == null); + Debug.Assert(_dsElement != null); + + DataSet? dataSet = (ds != null) ? ds : dt!.DataSet; if (dataSet != null) { _dsElement.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(dataSet.DataSetName)); _dsElement.SetAttribute(Keywords.MSD_ISDATASET, Keywords.MSDNS, Keywords.TRUE); if (ds == null) - _dsElement.SetAttribute(Keywords.MSD_MAINDATATABLE, Keywords.MSDNS, XmlConvert.EncodeLocalName(((dt.Namespace.Length == 0) ? dt.TableName : (dt.Namespace + ":" + dt.TableName)))); + _dsElement.SetAttribute(Keywords.MSD_MAINDATATABLE, Keywords.MSDNS, XmlConvert.EncodeLocalName(((dt!.Namespace.Length == 0) ? dt.TableName : (dt.Namespace + ":" + dt.TableName)))); // Add CaseSensitive and locale properties if (dataSet.CaseSensitive) @@ -1062,14 +1065,14 @@ namespace System.Data internal void SetPath(XmlWriter xw) { - FileStream fs = null; + FileStream? fs = null; - DataTextWriter sw = xw as DataTextWriter; + DataTextWriter? sw = xw as DataTextWriter; fs = (sw != null) ? sw.BaseStream as FileStream : null; if (fs == null) { - XmlTextWriter textw = xw as XmlTextWriter; + XmlTextWriter? textw = xw as XmlTextWriter; if (textw == null) return; fs = textw.BaseStream as FileStream; @@ -1101,17 +1104,17 @@ namespace System.Data doc.Save(xw); } - internal void Save(DataSet ds, DataTable dt, XmlWriter xw) + internal void Save(DataSet ds, DataTable? dt, XmlWriter xw) { Save(ds, dt, xw, false); } - internal void Save(DataSet ds, DataTable dt, XmlWriter xw, bool writeHierarchy) + internal void Save(DataSet? ds, DataTable? dt, XmlWriter xw, bool writeHierarchy) { Save(ds, dt, xw, writeHierarchy, null); } - internal void Save(DataSet ds, DataTable dt, XmlWriter xw, bool writeHierarchy, Converter multipleTargetConverter) + internal void Save(DataSet? ds, DataTable? dt, XmlWriter xw, bool writeHierarchy, Converter? multipleTargetConverter) { _targetConverter = multipleTargetConverter; @@ -1127,7 +1130,6 @@ namespace System.Data SchemaTree(doc, xw, ds, dt, writeHierarchy); } - internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) { XmlElement root = dc.CreateElement(Keywords.MSD, Keywords.MSD_RELATION, Keywords.MSDNS); @@ -1147,7 +1149,7 @@ namespace System.Data DataColumn[] key = rel.ParentKey.ColumnsReference; string text = key[0].EncodedColumnName; - StringBuilder builder = null; + StringBuilder? builder = null; if (1 < key.Length) { builder = new StringBuilder(); @@ -1184,7 +1186,7 @@ namespace System.Data return root; } - private static XmlElement FindSimpleType(XmlElement schema, string name) + private static XmlElement? FindSimpleType(XmlElement schema, string name) { for (XmlNode n = schema.FirstChild; n != null; n = n.NextSibling) { @@ -1202,17 +1204,17 @@ namespace System.Data internal XmlElement GetSchema(string NamespaceURI) { - XmlElement schemaEl = (XmlElement)_namespaces[NamespaceURI]; + XmlElement? schemaEl = (XmlElement?)_namespaces![NamespaceURI]; if (schemaEl == null) { - schemaEl = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); + schemaEl = _dc!.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); WriteSchemaRoot(_dc, schemaEl, NamespaceURI); if (!string.IsNullOrEmpty(NamespaceURI)) { string prefix = Keywords.APP + Convert.ToString(++_prefixCount, CultureInfo.InvariantCulture); - _sRoot.SetAttribute("xmlns:" + prefix, NamespaceURI); + _sRoot!.SetAttribute("xmlns:" + prefix, NamespaceURI); schemaEl.SetAttribute("xmlns:" + prefix, NamespaceURI); - _prefixes[NamespaceURI] = prefix; + _prefixes![NamespaceURI] = prefix; } _namespaces[NamespaceURI] = schemaEl; } @@ -1221,6 +1223,8 @@ namespace System.Data internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, XmlElement schema) { + Debug.Assert(_prefixes != null); + string keyword = Keywords.TYPE; if (col.ColumnMapping == MappingType.SimpleContent) keyword = Keywords.BASE; @@ -1228,19 +1232,19 @@ namespace System.Data if (col.SimpleType != null) { // generate simpleType node - SimpleType stNode = col.SimpleType; + SimpleType? stNode = col.SimpleType; while (stNode != null) { // for remoting, set the msdata:targetNamespace for the simpleType. XmlNode type; - string name = stNode.Name; + string? name = stNode.Name; if (name != null && name.Length != 0) { // For remoting, always need to work with root schema's namespace string nSpace = (_schFormat != SchemaFormat.Remoting) ? stNode.Namespace : - (col.Table.DataSet != null ? col.Table.DataSet.Namespace : col.Table.Namespace); + (col.Table!.DataSet != null ? col.Table.DataSet.Namespace : col.Table.Namespace); // for remoting we need to use columns NS, for other cases it is wrong to get Columns NS, we need to take type's namespace XmlElement schNode = GetSchema(nSpace); @@ -1253,7 +1257,7 @@ namespace System.Data if (stNode == col.SimpleType) { - string prefix = (string)_prefixes[nSpace]; + string? prefix = (string?)_prefixes[nSpace]; // set the columns's type if (prefix != null && prefix.Length > 0) { @@ -1267,7 +1271,7 @@ namespace System.Data // set the root to the actual type, do not overwrite it in the iteration. } - XmlElement elmSimpeType = FindSimpleType(schNode, name); + XmlElement? elmSimpeType = FindSimpleType(schNode, name); if (elmSimpeType == null) { // if we don't have the defenition for this simpleType yet. Add it @@ -1391,7 +1395,7 @@ namespace System.Data } else { // if it does not have any parent table , then it should inherit NS from DataSet - tgNamespace = _ds.Namespace; + tgNamespace = _ds!.Namespace; } } return tgNamespace; @@ -1399,6 +1403,9 @@ namespace System.Data internal XmlElement HandleColumn(DataColumn col, XmlDocument dc, XmlElement schema, bool fWriteOrdinal) { + Debug.Assert(_prefixes != null); + Debug.Assert(_dc != null); + XmlElement root; int minOccurs; @@ -1412,7 +1419,7 @@ namespace System.Data if (col.Namespace.Length == 0) { - DataTable _table = col.Table; + DataTable _table = col.Table!; // We need to travese the hirerarchy to find the targetnamepace string tgNamespace = FindTargetNamespace(_table); if (col.Namespace != tgNamespace) @@ -1480,17 +1487,16 @@ namespace System.Data if (_schFormat == SchemaFormat.Remoting) root.SetAttribute(Keywords.TARGETNAMESPACE, Keywords.MSDNS, col.Namespace); - else { - if ((col.Namespace != (col.Table.TypeName.IsEmpty ? col.Table.Namespace : col.Table.TypeName.Namespace)) && (col.Namespace.Length != 0)) + if ((col.Namespace != (col.Table!.TypeName.IsEmpty ? col.Table.Namespace : col.Table.TypeName.Namespace)) && (col.Namespace.Length != 0)) { XmlElement schNode = GetSchema(col.Namespace); if (FindTypeNode(schNode, col.EncodedColumnName) == null) schNode.AppendChild(root); root = _dc.CreateElement(Keywords.XSD_PREFIX, refString, Keywords.XSDNS); root.SetAttribute(Keywords.REF, _prefixes[col.Namespace] + ":" + col.EncodedColumnName); - if (col.Table.Namespace != _ds.Namespace) + if (col.Table.Namespace != _ds!.Namespace) { _ = GetSchema(col.Table.Namespace); } @@ -1526,7 +1532,7 @@ namespace System.Data { AcceptRejectRule.Cascade => "Cascade", AcceptRejectRule.None => "None", - _ => null, + _ => null!, }; internal static string TranslateRule(Rule rule) => @@ -1536,7 +1542,7 @@ namespace System.Data Rule.None => "None", Rule.SetNull => "SetNull", Rule.SetDefault => "SetDefault", - _ => null, + _ => null!, }; internal void AppendChildWithoutRef(XmlElement node, string Namespace, XmlElement el, string refString) @@ -1546,7 +1552,7 @@ namespace System.Data schNode.AppendChild(el); } - internal XmlElement FindTypeNode(XmlElement node, string strType) + internal XmlElement? FindTypeNode(XmlElement node, string strType) { if (node == null) return null; @@ -1604,7 +1610,7 @@ namespace System.Data if (col.DataType != typeof(int)) return false; - string generatedname = col.Table.TableName + "_Id"; + string generatedname = col.Table!.TableName + "_Id"; if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0")) return true; @@ -1625,7 +1631,7 @@ namespace System.Data continue; //ok if we are here it means that we have a 1column-1column relation - generatedname = rel.ParentColumnsReference[0].Table.TableName + "_Id"; + generatedname = rel.ParentColumnsReference[0].Table!.TableName + "_Id"; } if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0")) @@ -1662,7 +1668,7 @@ namespace System.Data internal static bool AutoGenerated(ForeignKeyConstraint fk, bool checkRelation) { // for now we use just this simple logic for the columns. - DataRelation rel = fk.FindParentRelation(); + DataRelation? rel = fk.FindParentRelation(); if (checkRelation) { if (rel == null) @@ -1701,6 +1707,10 @@ namespace System.Data internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement schema, bool genNested) { + Debug.Assert(_prefixes != null); + Debug.Assert(_dc != null); + Debug.Assert(_dsElement != null); + XmlElement root = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); bool fWriteOrdinals = false; bool fUnqualified = false; @@ -1829,12 +1839,12 @@ namespace System.Data if (!table.TypeName.IsEmpty) { if (_schFormat != SchemaFormat.Remoting) - root.SetAttribute(Keywords.TYPE, NewDiffgramGen.QualifiedName((string)_prefixes[table.TypeName.Namespace], table.TypeName.Name)); + root.SetAttribute(Keywords.TYPE, NewDiffgramGen.QualifiedName((string)_prefixes[table.TypeName.Namespace]!, table.TypeName.Name)); } - XmlElement compositor = null; + XmlElement? compositor = null; - DataColumn colTxt = table.XmlText; + DataColumn? colTxt = table.XmlText; if (colTxt != null) { @@ -1931,7 +1941,7 @@ namespace System.Data if (childTable.NestedParentsCount <= 1) GetSchema(childTable.Namespace).AppendChild(NestedTable); NestedTable = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); - NestedTable.SetAttribute(Keywords.REF, ((string)_prefixes[childTable.Namespace]) + ':' + childTable.EncodedTableName); + NestedTable.SetAttribute(Keywords.REF, ((string)_prefixes[childTable.Namespace]!) + ':' + childTable.EncodedTableName); compositor.AppendChild(NestedTable); } @@ -1961,12 +1971,12 @@ namespace System.Data if (_schFormat != SchemaFormat.Remoting) { GetSchema(table.Namespace); // to ensure prefix handling - xpathprefix = table.Namespace.Length != 0 ? (string)_prefixes[table.Namespace] + ':' : string.Empty; + xpathprefix = table.Namespace.Length != 0 ? (string)_prefixes[table.Namespace]! + ':' : string.Empty; } for (int i = 0; i < constraints.Count; i++) { - XmlElement constraint = null; + XmlElement? constraint = null; DataColumn[] fields; if (constraints[i] is UniqueConstraint) @@ -2051,13 +2061,13 @@ namespace System.Data continue; - DataRelation rel = foreign.FindParentRelation(); + DataRelation? rel = foreign.FindParentRelation(); // special case of the ghosted constraints: fields = foreign.RelatedColumnsReference; - UniqueConstraint _constraint = (UniqueConstraint)foreign.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fields)); + UniqueConstraint? _constraint = (UniqueConstraint?)foreign.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fields)); if (_constraint == null) { @@ -2111,7 +2121,7 @@ namespace System.Data constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(foreign.SchemaName)); if ((_ds == null) || (_ds.Tables.InternalIndexOf(foreign.RelatedTable.TableName) == -3)) // if there is a conflicting name/namespace only - constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, foreign.Table.Namespace); + constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, foreign.Table!.Namespace); if (_constraint == null) constraint.SetAttribute(Keywords.REFER, XmlConvert.EncodeLocalName(foreign.SchemaName)); @@ -2235,12 +2245,12 @@ namespace System.Data internal sealed class NewDiffgramGen { internal XmlDocument _doc; - internal DataSet _ds; - internal DataTable _dt; - internal XmlWriter _xmlw; + internal DataSet? _ds; + internal DataTable? _dt; + internal XmlWriter _xmlw = default!; // Late-initialized private bool _fBefore; private bool _fErrors; - internal Hashtable _rowsOrder; + internal Hashtable _rowsOrder = default!; // Always initialized in DoAssignments private readonly ArrayList _tables = new ArrayList(); private readonly bool _writeHierarchy; @@ -2293,12 +2303,12 @@ namespace System.Data int rows = 0; for (int i = 0; i < tables.Count; i++) { - rows += ((DataTable)tables[i]).Rows.Count; + rows += ((DataTable)tables[i]!).Rows.Count; } _rowsOrder = new Hashtable(rows); for (int i = 0; i < tables.Count; i++) { - DataTable dt = (DataTable)tables[i]; + DataTable dt = (DataTable)tables[i]!; DataRowCollection rc = dt.Rows; rows = rc.Count; for (int j = 0; j < rows; j++) @@ -2310,7 +2320,7 @@ namespace System.Data { for (int i = 0; i < _tables.Count; i++) { - if (((DataTable)_tables[i]).Rows.Count > 0) + if (((DataTable)_tables[i]!).Rows.Count > 0) return false; } return true; @@ -2321,7 +2331,7 @@ namespace System.Data Save(xmlw, null); } - internal void Save(XmlWriter xmlw, DataTable table) + internal void Save(XmlWriter xmlw, DataTable? table) { _xmlw = DataTextWriter.CreateWriter(xmlw); @@ -2335,13 +2345,13 @@ namespace System.Data if (table != null) new XmlDataTreeWriter(table, _writeHierarchy).SaveDiffgramData(_xmlw, _rowsOrder); else - new XmlDataTreeWriter(_ds).SaveDiffgramData(_xmlw, _rowsOrder); + new XmlDataTreeWriter(_ds!).SaveDiffgramData(_xmlw, _rowsOrder); // Walk the xd using relational apis and create nodes in nodeRoot appropriately. if (table == null) { - for (int i = 0; i < _ds.Tables.Count; ++i) + for (int i = 0; i < _ds!.Tables.Count; ++i) { GenerateTable(_ds.Tables[i]); } @@ -2350,7 +2360,7 @@ namespace System.Data { for (int i = 0; i < _tables.Count; i++) { - GenerateTable((DataTable)_tables[i]); + GenerateTable((DataTable)_tables[i]!); } } @@ -2359,7 +2369,7 @@ namespace System.Data if (table == null) { - for (int i = 0; i < _ds.Tables.Count; ++i) + for (int i = 0; i < _ds!.Tables.Count; ++i) { GenerateTableErrors(_ds.Tables[i]); } @@ -2368,7 +2378,7 @@ namespace System.Data { for (int i = 0; i < _tables.Count; i++) { - GenerateTableErrors((DataTable)_tables[i]); + GenerateTableErrors((DataTable)_tables[i]!); } } @@ -2471,10 +2481,10 @@ namespace System.Data DataTable table = row.Table; int colCount = table.Columns.Count; string rowIDString = table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture); - string parentId = null; + string? parentId = null; if ((state == DataRowState.Deleted) && (row.Table.NestedParentRelations.Length != 0)) { - DataRow parentRow = row.GetNestedParentRow(DataRowVersion.Original); + DataRow? parentRow = row.GetNestedParentRow(DataRowVersion.Original); if (parentRow != null) { parentId = parentRow.Table.TableName + parentRow.rowID.ToString(CultureInfo.InvariantCulture); @@ -2495,7 +2505,7 @@ namespace System.Data if (parentId != null) _xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFPID, Keywords.DFFNS, parentId); - _xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder[row].ToString()); + _xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder[row]!.ToString()); for (int colNum = 0; colNum < colCount; ++colNum) { if ((row.Table.Columns[colNum].ColumnMapping == MappingType.Attribute) || @@ -2513,7 +2523,7 @@ namespace System.Data private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version) { - string value = null; + string? value = null; value = col.GetColumnValueAsString(row, version); // this is useless for CTD if (value == null) @@ -2580,7 +2590,7 @@ namespace System.Data // this column's type does not implement IXmlSerializable, so we need to handle serialization via XmlSerializer if (columnValue.GetType() != col.DataType) { // throw if polymorphism; not supported - throw ExceptionBuilder.PolymorphismNotSupported(valuesType.AssemblyQualifiedName); + throw ExceptionBuilder.PolymorphismNotSupported(valuesType.AssemblyQualifiedName!); } // therefore we are skipping the start element, but by passing XmlRootAttribute with the same name as // we open the start element (column's name), XmlSerializer will open and close it for us @@ -2639,21 +2649,19 @@ namespace System.Data // DataTreeWriter internal sealed class XmlDataTreeWriter { - private XmlWriter _xmlw; + private XmlWriter? _xmlw; - private readonly DataSet _ds; - private readonly DataTable _dt; + private readonly DataSet? _ds; + private readonly DataTable? _dt; private readonly ArrayList _dTables = new ArrayList(); private readonly DataTable[] _topLevelTables; private readonly bool _fFromTable; // also means no hierarchy private bool _isDiffgram; - private Hashtable _rowsOrder; + private Hashtable? _rowsOrder; private readonly bool _writeHierarchy; - - internal XmlDataTreeWriter(DataSet ds) { _ds = ds; @@ -2693,7 +2701,7 @@ namespace System.Data ArrayList topTables = new ArrayList(); for (int i = 0; i < _dTables.Count; i++) { - DataTable table = (DataTable)_dTables[i]; + DataTable table = (DataTable)_dTables[i]!; if (table.ParentRelations.Count == 0) topTables.Add(table); else @@ -2765,14 +2773,16 @@ namespace System.Data internal void SaveDiffgramData(XmlWriter xw, Hashtable rowsOrder) { + Debug.Assert(_ds != null || _dt != null); + _xmlw = DataTextWriter.CreateWriter(xw); _isDiffgram = true; _rowsOrder = rowsOrder; - string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt.Namespace.Length == 0) ? "" : _dt.Prefix); + string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); if (_ds == null || _ds.DataSetName == null || _ds.DataSetName.Length == 0) - _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, (_dt.Namespace == null) ? "" : _dt.Namespace); + _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, (_dt!.Namespace == null) ? "" : _dt.Namespace); else _xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace); @@ -2780,7 +2790,7 @@ namespace System.Data for (int i = 0; i < _dTables.Count; i++) { - DataTable tempTable = ((DataTable)_dTables[i]); + DataTable tempTable = ((DataTable)_dTables[i]!); foreach (DataRow row in tempTable.Rows) { if (row.RowState == DataRowState.Deleted) @@ -2788,7 +2798,7 @@ namespace System.Data int nestedParentRowCount = row.GetNestedParentCount(); if (nestedParentRowCount == 0) { - DataTable tempDT = ((DataTable)_dTables[i]); + DataTable tempDT = ((DataTable)_dTables[i]!); XmlDataRowWriter(row, tempDT.EncodedTableName); } else if (nestedParentRowCount > 1) @@ -2806,12 +2816,14 @@ namespace System.Data internal void Save(XmlWriter xw, bool writeSchema) { + Debug.Assert(_ds != null || _dt != null); + _xmlw = DataTextWriter.CreateWriter(xw); int countTopTable = _topLevelTables.Length; bool fWriteDSElement = true; - string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt.Namespace.Length == 0) ? "" : _dt.Prefix); + string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); if (!writeSchema && _ds != null && _ds._fTopLevelTable && countTopTable == 1) { @@ -2823,7 +2835,7 @@ namespace System.Data { if (_ds == null) { - _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _dt.Namespace); + _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _dt!.Namespace); } else { @@ -2835,7 +2847,7 @@ namespace System.Data for (int i = 0; i < _dTables.Count; i++) { - if (((DataTable)_dTables[i])._xmlText != null) + if (((DataTable)_dTables[i]!)._xmlText != null) { _xmlw.WriteAttributeString(Keywords.XMLNS, Keywords.XSI, Keywords.XSD_XMLNS_NS, Keywords.XSINS); break; @@ -2846,29 +2858,29 @@ namespace System.Data { if (!_fFromTable) { - new XmlTreeGen(SchemaFormat.Public).Save(_ds, _xmlw); + new XmlTreeGen(SchemaFormat.Public).Save(_ds!, _xmlw); } else { - new XmlTreeGen(SchemaFormat.Public).Save(null, _dt, _xmlw, _writeHierarchy); + new XmlTreeGen(SchemaFormat.Public).Save(null, _dt!, _xmlw, _writeHierarchy); } } } for (int i = 0; i < _dTables.Count; i++) { - foreach (DataRow row in ((DataTable)_dTables[i]).Rows) + foreach (DataRow row in ((DataTable)_dTables[i]!).Rows) { if (row.RowState == DataRowState.Deleted) continue; int parentRowCount = row.GetNestedParentCount(); if (parentRowCount == 0) { - XmlDataRowWriter(row, ((DataTable)_dTables[i]).EncodedTableName); + XmlDataRowWriter(row, ((DataTable)_dTables[i]!).EncodedTableName); } else if (parentRowCount > 1) { - DataTable dt = (DataTable)_dTables[i]; + DataTable dt = (DataTable)_dTables[i]!; throw ExceptionBuilder.MultipleParentRows(dt.Namespace.Length == 0 ? dt.TableName : (dt.Namespace + dt.TableName)); // At all times a nested row can only have 0 or 1 parents, never more than 1 } @@ -2896,6 +2908,8 @@ namespace System.Data internal void XmlDataRowWriter(DataRow row, string encodedTableName) { + Debug.Assert(_xmlw != null); + object value; string prefix = (row.Table.Namespace.Length == 0) ? "" : row.Table.Prefix; @@ -2905,7 +2919,7 @@ namespace System.Data { _xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFID, Keywords.DFFNS, row.Table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture)); - _xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder[row].ToString()); + _xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder![row]!.ToString()); if (row.RowState == DataRowState.Added) { @@ -3005,7 +3019,7 @@ namespace System.Data { // startElement is skipped: this column's type does not implement IXmlSerializable, need to go via XmlSerializer if (value.GetType() != col.DataType) { // throw if polymorphism; not supported - throw ExceptionBuilder.PolymorphismNotSupported(valuesType.AssemblyQualifiedName); + throw ExceptionBuilder.PolymorphismNotSupported(valuesType.AssemblyQualifiedName!); } // therefore we are skipping the start element, but by passing XmlRootAttribute with the same name as // we open the start element (column's name), XmlSerializer will open and close it for us @@ -3061,7 +3075,7 @@ namespace System.Data internal static bool PreserveSpace(object value) { Debug.Assert(value != null, "Value can not be null"); - string tempValue = value.ToString(); + string tempValue = value.ToString()!; if (tempValue.Length == 0) { return false; @@ -3091,11 +3105,11 @@ namespace System.Data _xmltextWriter = w; } - internal Stream BaseStream + internal Stream? BaseStream { get { - XmlTextWriter textWriter = _xmltextWriter as XmlTextWriter; + XmlTextWriter? textWriter = _xmltextWriter as XmlTextWriter; if (null != textWriter) { return textWriter.BaseStream; diff --git a/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs index 4b119a3..74a1721 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + namespace System.Xml { // Iterates over non-attribute nodes diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs b/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs index 8b0c3d0..ec88cf9 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Xml.XPath; #pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs index 40fc922..768834a 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Data; using System.Diagnostics; diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs index fbc3e1d..95a2e50 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Collections; using System.Data; using System.Diagnostics; diff --git a/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs b/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs index 115b0a5..18dbd1e 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Data; namespace System.Xml diff --git a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs index 2f124b9..5be8426 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Diagnostics; using System.Text; diff --git a/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs index af4d31e..26bc84f 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Diagnostics; #pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument diff --git a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs index 1608d7b..d313230 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Data; using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs index 751e901..77ed74c 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Data; using System.Diagnostics; using System.Threading; diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index 692168e..7c8ce6d 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + using System.Collections; using System.Collections.Generic; using System.ComponentModel; diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs index a161154..957c0c6 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// TODO: Enable after System.Private.Xml is annotated +#nullable disable + #pragma warning disable 618 // ignore obsolete warning about XmlDataDocument namespace System.Xml