diff --git a/Directory.Build.props b/Directory.Build.props index c2c63465..4d4857dc 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -28,5 +28,7 @@ See full changelog at https://github.com/sillsdev/liblcm/blob/develop/CHANGELOG. false $(MSBuildThisFileDirectory)/CHANGELOG.md false + 9.0 + warnings diff --git a/src/CSTools/Tools/Tools.csproj b/src/CSTools/Tools/Tools.csproj index df4f2dda..beaacd6b 100644 --- a/src/CSTools/Tools/Tools.csproj +++ b/src/CSTools/Tools/Tools.csproj @@ -16,5 +16,9 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/CSTools/Tools/dfa.cs b/src/CSTools/Tools/dfa.cs index 56945d88..b54c2462 100644 --- a/src/CSTools/Tools/dfa.cs +++ b/src/CSTools/Tools/dfa.cs @@ -602,7 +602,7 @@ public override int Match(string str, int pos, int max) if (m_sub!=null) a = m_sub.Match(str, pos, max); if (m_alt!=null) - b = m_sub.Match(str, pos, max); + b = m_alt.Match(str, pos, max); return (a>b)?a:b; } public override void Build(Nfa nfa) diff --git a/src/CSTools/Tools/genbase.cs b/src/CSTools/Tools/genbase.cs index aef67210..decbf6de 100644 --- a/src/CSTools/Tools/genbase.cs +++ b/src/CSTools/Tools/genbase.cs @@ -8,6 +8,7 @@ using System; using System.IO; using System.Text; +using System.Diagnostics.CodeAnalysis; using YYClass; namespace SIL.LCModel.Tools @@ -169,12 +170,8 @@ public void EmitClassDefin(string b,ref int p,int max,CsReader inf,string defbas } m_outFile.WriteLine("}"); } - /// - /// - /// - /// - /// - /// + + [DoesNotReturn] public void Error(int n,int p,string str) { Console.WriteLine(str); @@ -185,6 +182,7 @@ public void Error(int n,int p,string str) } erh.Error(new CSToolsFatalException(n,line(p),position(p),"",str)); } + public virtual int line(int pos) { return 0; } public virtual int position(int pos) { return pos; } public virtual string Saypos(int pos) { return "at "+pos+": "; } diff --git a/src/CSTools/Tools/lexer.cs b/src/CSTools/Tools/lexer.cs index efdcd10c..ef1cb922 100644 --- a/src/CSTools/Tools/lexer.cs +++ b/src/CSTools/Tools/lexer.cs @@ -6,8 +6,10 @@ using System.IO; using System.Text; using System.Globalization; +using System.Diagnostics.CodeAnalysis; //using System.Runtime.Serialization.Formatters.Binary; + namespace SIL.LCModel.Tools { @@ -384,7 +386,7 @@ public static object create(string cls_name,Lexer yyl) yyl.tokens.erh.Error(new CSToolsException(6,yyl,cls_name,String.Format("no factory for {0}",cls_name))); try { - return cr(yyl); + return cr!(yyl); } catch (CSToolsException x) { @@ -605,7 +607,7 @@ public static implicit operator int (SYMBOL s) // 4.0c s = (SYMBOL)d; try { - rv =(int)d; + rv =(int)d!; } catch(Exception e) { @@ -638,8 +640,8 @@ public virtual bool Pass(Symbols syms,int snum,out ParserEntry entry) string s = string.Format("No parsinginfo for symbol {0}",yyname()); syms.erh.Error(new CSToolsFatalException(9,yylx,yyname(),s)); } - bool r = pi.m_parsetable.Contains(snum); - entry = r?((ParserEntry)pi.m_parsetable[snum]):null; + bool r = pi != null && pi.m_parsetable.Contains(snum); + entry = pi != null && r ? ((ParserEntry)pi.m_parsetable[snum]) : null; return r; } public virtual string yyname() { return "SYMBOL"; } @@ -675,8 +677,8 @@ public override bool Pass(Symbols syms,int snum, out ParserEntry entry) ParsingInfo pi = (ParsingInfo)syms.literalInfo[m_str]; if (pi==null) syms.erh.Error(new CSToolsException(10,yylx,m_str,String.Format("Parser does not recognise literal <{0}>",m_str))); - bool r = pi.m_parsetable.Contains(snum); - entry = r?((ParserEntry)pi.m_parsetable[snum]):null; + bool r = pi != null && pi.m_parsetable.Contains(snum); + entry = pi != null && r ? ((ParserEntry)pi.m_parsetable[snum]) : null; return r; } public override bool IsTerminal() { return true; } @@ -971,20 +973,22 @@ public virtual void Error(Exception e) { counter++; if (throwExceptions || (e is CSToolsFatalException)) - throw(e); - if (e is CSToolsException) + throw e; + if (e is CSToolsException x) { - CSToolsException x = (CSToolsException)e; if (x.handled) return; x.handled = true; -// if (x.nLine !=0 || x.nChar!=0) -// { -// Console.WriteLine("line "+x.nLine+", char "+x.nChar+": "+x.Message); -// return; -// } + } Console.WriteLine(e.Message); } + + [DoesNotReturn] + public virtual void Error(CSToolsFatalException e) + { + counter++; + throw e; + } } } \ No newline at end of file diff --git a/src/CSTools/Tools/parser.cs b/src/CSTools/Tools/parser.cs index de728f9c..7b2ebf10 100644 --- a/src/CSTools/Tools/parser.cs +++ b/src/CSTools/Tools/parser.cs @@ -1504,7 +1504,7 @@ protected bool Error(ref ParseStackEntry top, string str) newtop = pe.m_action.Action(this); // before we change the stack m_ungot = top.m_value; Pop(ref top,((ParserReduce)pe).m_depth,er); - newtop.pos = top.m_value.pos; + newtop!.pos = top.m_value.pos; top.m_value = newtop; } else @@ -1554,6 +1554,8 @@ SYMBOL Parse() ParseStackEntry top = new ParseStackEntry(this,0,NextSym()); for (;;) { + if (top.m_value == null) + throw new NullReferenceException("Stack entry m_value cannot be null"); string cnm = top.m_value.yyname(); if (m_debug) { @@ -1693,7 +1695,8 @@ public static object create(string cls_name,Parser yyp) yyp.m_symbols.erh.Error(new CSToolsException(16,yyp.m_lexer,"no factory for {"+cls_name+")")); try { - return cr(yyp); + if (cr != null) + return cr(yyp); } catch (CSToolsException e) { diff --git a/src/CSTools/pg/pg.cs b/src/CSTools/pg/pg.cs index e3ab8f51..19504f4b 100644 --- a/src/CSTools/pg/pg.cs +++ b/src/CSTools/pg/pg.cs @@ -9,6 +9,7 @@ using System.Collections; using System.IO; using System.Text; +using System.Diagnostics.CodeAnalysis; using SIL.LCModel.Tools; public class PrecReference : TOKEN @@ -782,7 +783,7 @@ internal void ParseProduction() Error(39,m_tok.pos,string.Format("Illegal left hand side <{0}> for production",m_tok.yytext)); if (m_symbols.m_startSymbol==null) m_symbols.m_startSymbol = lhs; - if (lhs.m_symtype==CSymbol.SymType.unknown) + if (lhs!.m_symtype==CSymbol.SymType.unknown) lhs.m_symtype = CSymbol.SymType.nonterminal; if ((!lhs.m_defined) && lhs.m_prods.Count==0) { // lhs not defined in %symbol statement and not previously a lhs diff --git a/src/SIL.LCModel.Core/Phonology/PhonEnvRecognizer.cs b/src/SIL.LCModel.Core/Phonology/PhonEnvRecognizer.cs index 03cf808a..f0204797 100644 --- a/src/SIL.LCModel.Core/Phonology/PhonEnvRecognizer.cs +++ b/src/SIL.LCModel.Core/Phonology/PhonEnvRecognizer.cs @@ -155,7 +155,7 @@ public bool Result public static bool CanInsertItem(string sEnv, int ichEnd, int ichAnchor) { Debug.Assert(sEnv != null); - Debug.Assert(ichEnd <= sEnv.Length && ichAnchor <= sEnv.Length); + Debug.Assert(ichEnd <= sEnv!.Length && ichAnchor <= sEnv.Length); if (ichEnd < 0 || ichAnchor < 0) return false; int ichSlash = sEnv.IndexOf('/'); @@ -199,7 +199,7 @@ public static bool CanInsertItem(string sEnv, int ichEnd, int ichAnchor) public static bool CanInsertHashMark(string sEnv, int ichEnd, int ichAnchor) { Debug.Assert(sEnv != null); - Debug.Assert(ichEnd <= sEnv.Length && ichAnchor <= sEnv.Length); + Debug.Assert(ichEnd <= sEnv!.Length && ichAnchor <= sEnv.Length); if (ichEnd < 0 || ichAnchor < 0) return false; int ichSlash = sEnv.IndexOf('/'); @@ -297,10 +297,10 @@ public static void CreateErrorMessageFromXml(string strRep1, string sXmlMessage, // there were XML reserved characters in the environment. // until we get that fixed, at least don't crash, just draw squiggly under the entire word xdoc.LoadXml(sXmlMessage); - XmlAttribute posAttr = xdoc.DocumentElement.Attributes["pos"]; + XmlAttribute posAttr = xdoc.DocumentElement!.Attributes["pos"]; pos = (posAttr != null) ? Convert.ToInt32(posAttr.Value) : 0; XmlAttribute statusAttr = xdoc.DocumentElement.Attributes["status"]; - sStatus = statusAttr.InnerText; + sStatus = statusAttr!.InnerText; } catch { diff --git a/src/SIL.LCModel.Core/SIL.LCModel.Core.csproj b/src/SIL.LCModel.Core/SIL.LCModel.Core.csproj index c448c981..7f94884e 100644 --- a/src/SIL.LCModel.Core/SIL.LCModel.Core.csproj +++ b/src/SIL.LCModel.Core/SIL.LCModel.Core.csproj @@ -25,6 +25,10 @@ SIL.LCModel.Core provides a base library with core functionality. + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/SIL.LCModel.Core/Scripture/MultilingScrBooks.cs b/src/SIL.LCModel.Core/Scripture/MultilingScrBooks.cs index 23fb2541..e5e6f924 100644 --- a/src/SIL.LCModel.Core/Scripture/MultilingScrBooks.cs +++ b/src/SIL.LCModel.Core/Scripture/MultilingScrBooks.cs @@ -464,9 +464,11 @@ public virtual string GetBookAbbrev(int nBook) // No abbreviation found in primary writing system; get SIL code instead wsNames = GetWsNames(kWsSilCodes); // SIL codes - Debug.Assert (wsNames != null); + if (wsNames == null) + throw new InvalidOperationException("Could not get SIL codes"); sAbbrev = wsNames.Name[nBook - 1]; // full SIL code is the .Name - Debug.Assert(sAbbrev != null); + if (sAbbrev == null) + throw new InvalidOperationException("Could not get abbreviation for book " + nBook); return sAbbrev; } diff --git a/src/SIL.LCModel.Core/Text/CustomIcu.cs b/src/SIL.LCModel.Core/Text/CustomIcu.cs index 61d7fcaa..62f03526 100644 --- a/src/SIL.LCModel.Core/Text/CustomIcu.cs +++ b/src/SIL.LCModel.Core/Text/CustomIcu.cs @@ -178,9 +178,10 @@ public static void InitIcuDataDir() // application (e.g. Flex & Paratext) if (Platform.IsWindows) { - var executingAssemblyFolder = Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path); + var executingAssemblyFolder = Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().Location).Path); var assemblyDir = Path.GetDirectoryName(executingAssemblyFolder); - // ReSharper disable once AssignNullToNotNullAttribute -- The directory of the executing assembly will not be null + if (assemblyDir == null) + throw new InvalidOperationException("Could not get assembly directory from " + executingAssemblyFolder); var icu32Path = Path.Combine(assemblyDir, "lib", "win-x86"); var icu64Path = Path.Combine(assemblyDir, "lib", "win-x64"); var flexIcu32Path = Path.Combine(assemblyDir, "lib", "x86"); diff --git a/src/SIL.LCModel.Core/Text/PUACharacter.cs b/src/SIL.LCModel.Core/Text/PUACharacter.cs index 254b2c31..1e94f3d2 100644 --- a/src/SIL.LCModel.Core/Text/PUACharacter.cs +++ b/src/SIL.LCModel.Core/Text/PUACharacter.cs @@ -1018,12 +1018,11 @@ protected int CompareRegions(string property2) public override int CompareTo(object obj) { // if they give us a UCDCharacter, compare Properties - if (obj is UCDCharacter) + if (obj is UCDCharacter c) { - UCDCharacter ucdChar = obj as UCDCharacter; - if (SameRegion(ucdChar)) - return MiscUtils.CompareHex(CodePoint, ucdChar.CodePoint); - return CompareRegions(ucdChar.Property); + if (SameRegion(c)) + return MiscUtils.CompareHex(CodePoint, c.CodePoint); + return CompareRegions(c.Property); } // if they give us a string, assume its a codepoint else if (obj is string) diff --git a/src/SIL.LCModel.Core/Text/TsString.cs b/src/SIL.LCModel.Core/Text/TsString.cs index a6c3518f..2f657328 100644 --- a/src/SIL.LCModel.Core/Text/TsString.cs +++ b/src/SIL.LCModel.Core/Text/TsString.cs @@ -459,7 +459,7 @@ private ITsString get_NormalizedFormAndFixOffsets(FwNormalizationMode nm, ArrayP // Note that our local mapping is from the start of this segment, but we want to keep track of indexes from the start // of the *string*. (Both the original string and the output, normalized string). So we adjust the indexes here. if (mapping.isFirstCharOfDecomposition) - stringOffsetMapping[segmentMin + mapping.origIdx] = outputLenSoFar + mapping.normIdx; + stringOffsetMapping![segmentMin + mapping.origIdx] = outputLenSoFar + mapping.normIdx; } } } @@ -489,7 +489,7 @@ private ITsString get_NormalizedFormAndFixOffsets(FwNormalizationMode nm, ArrayP resultBuilder.SetProperties(outputIdx, outputIdx + size, origProperties); // And if we also need to fix up offsets at the end, we keep track of the ones we'll need if (willFixOffsets && mapping.isFirstCharOfDecomposition) - stringOffsetMapping[segmentMin + mapping.origIdx] = outputLenSoFar + mapping.normIdx; + stringOffsetMapping![segmentMin + mapping.origIdx] = outputLenSoFar + mapping.normIdx; } } @@ -526,11 +526,11 @@ private ITsString get_NormalizedFormAndFixOffsets(FwNormalizationMode nm, ArrayP } if (willFixOffsets) { - stringOffsetMapping[segmentMin] = resultBuilder.Length; + stringOffsetMapping![segmentMin] = resultBuilder.Length; int ptrSize = Marshal.SizeOf(typeof(IntPtr)); for (int i = 0; i < numOffsetsToFix; i++) { - IntPtr offsetPtr = Marshal.ReadIntPtr(oldOffsetsToFix.IntPtr, i * ptrSize); + IntPtr offsetPtr = Marshal.ReadIntPtr(oldOffsetsToFix!.IntPtr, i * ptrSize); int oldOffset = Marshal.ReadInt32(offsetPtr); int newOffset; if (stringOffsetMapping.TryGetValue(oldOffset, out newOffset)) diff --git a/src/SIL.LCModel.Core/Text/TsStringUtils.cs b/src/SIL.LCModel.Core/Text/TsStringUtils.cs index b64ab04e..f8f1c9a6 100644 --- a/src/SIL.LCModel.Core/Text/TsStringUtils.cs +++ b/src/SIL.LCModel.Core/Text/TsStringUtils.cs @@ -1387,12 +1387,13 @@ public static ITsString MergeString(ITsString source, ITsString dest) /// ------------------------------------------------------------------------------------ public static ITsString MergeString(ITsString source, ITsString dest, bool fConcatenateIfBoth) { - string destText = (dest != null) ? dest.Text : null; - string sourceText = (source != null) ? source.Text : null; - - if (string.IsNullOrEmpty(destText) && !string.IsNullOrEmpty(sourceText)) + if (dest == null && source == null) + return null; + if (dest == null || string.IsNullOrEmpty(dest.Text)) return source; - else if (fConcatenateIfBoth && !string.IsNullOrEmpty(destText) && !string.IsNullOrEmpty(sourceText) && !dest.Equals(source)) + if (source == null || string.IsNullOrEmpty(source.Text)) + return dest; + if (fConcatenateIfBoth && !dest.Equals(source)) { // concatenate ITsStrBldr tsb = dest.GetBldr(); @@ -1633,6 +1634,12 @@ public static ITsTextProps PropsForWs(int ws) Justification = "If a tss is null, crunBoth will be 0, so we'll never try to access it.")] public static TsStringDiffInfo GetDiffsInTsStrings(ITsString tssOld, ITsString tssNew) { + if (tssOld == null && tssNew == null) + return null; + if (tssOld == null) + return new TsStringDiffInfo(0, tssNew.Length, 0, true); + if (tssNew == null) + return new TsStringDiffInfo(0, 0, tssOld.Length, true); // no diff found var ichMin = -1; @@ -1640,16 +1647,10 @@ public static TsStringDiffInfo GetDiffsInTsStrings(ITsString tssOld, ITsString t int crunOld = 0; int crunNew = 0; int cchNew = 0; - if (tssNew != null) - { - cchNew = tssNew.Length; - crunNew = tssNew.RunCount; - } - if (tssOld != null) - { - cchOld = tssOld.Length; - crunOld = tssOld.RunCount; - } + cchNew = tssNew.Length; + crunNew = tssNew.RunCount; + cchOld = tssOld.Length; + crunOld = tssOld.RunCount; var crunBoth = Math.Min(crunOld, crunNew); // Set ichMin to the index of the first character that is different or has different properties. diff --git a/src/SIL.LCModel.Core/WritingSystems/CoreWritingSystemDefinition.cs b/src/SIL.LCModel.Core/WritingSystems/CoreWritingSystemDefinition.cs index ef6ad773..2f35b90f 100644 --- a/src/SIL.LCModel.Core/WritingSystems/CoreWritingSystemDefinition.cs +++ b/src/SIL.LCModel.Core/WritingSystems/CoreWritingSystemDefinition.cs @@ -67,12 +67,16 @@ private void MainCharacterSetChanged(object sender, NotifyCollectionChangedEvent switch (e.Action) { case NotifyCollectionChangedAction.Add: + if (e.NewItems == null) throw new NullReferenceException("e.NewItems"); AddWordFormingOverrides(e.NewItems.Cast()); break; case NotifyCollectionChangedAction.Remove: + if (e.OldItems == null) throw new NullReferenceException("e.OldItems"); RemoveWordFormingOverrides(e.OldItems.Cast()); break; case NotifyCollectionChangedAction.Replace: + if (e.NewItems == null) throw new NullReferenceException("e.NewItems"); + if (e.OldItems == null) throw new NullReferenceException("e.OldItems"); RemoveWordFormingOverrides(e.OldItems.Cast()); AddWordFormingOverrides(e.NewItems.Cast()); break; diff --git a/src/SIL.LCModel.Core/WritingSystems/ValidCharacters.cs b/src/SIL.LCModel.Core/WritingSystems/ValidCharacters.cs index f73036d6..4667e839 100644 --- a/src/SIL.LCModel.Core/WritingSystems/ValidCharacters.cs +++ b/src/SIL.LCModel.Core/WritingSystems/ValidCharacters.cs @@ -596,7 +596,8 @@ public static IEnumerable ParseLegacyWordFormingCharOverrides(string pat { foreach (XmlNode charNode in charsList) { - string codepointStr = charNode.Attributes["val"].InnerText; + string codepointStr = charNode.Attributes?["val"]?.InnerText; + if (codepointStr == null) throw new InvalidOperationException("Could not get codepoint from " + charNode.OuterXml); int codepoint = Convert.ToInt32(codepointStr, 16); var c = (char) codepoint; result.Add(c.ToString(CultureInfo.InvariantCulture)); diff --git a/src/SIL.LCModel.Utils/FileUtils.cs b/src/SIL.LCModel.Utils/FileUtils.cs index 7b5f1b40..a2d2fea1 100644 --- a/src/SIL.LCModel.Utils/FileUtils.cs +++ b/src/SIL.LCModel.Utils/FileUtils.cs @@ -441,6 +441,8 @@ public static string ActualFilePath(string sPathname) return sPathname.Normalize(NormalizationForm.FormD); string sDir = Path.GetDirectoryName(sPathname); + if (sDir == null) + throw new InvalidOperationException("Could not get directory name from path " + sPathname); string sFile = Path.GetFileName(sPathname).Normalize(); if (!Platform.IsUnix) // Using IsUnix to decide if a file system is case sensitive { // isn't the best way since some Unix file systems are case diff --git a/src/SIL.LCModel.Utils/MiscUtils.cs b/src/SIL.LCModel.Utils/MiscUtils.cs index ec092460..763c4ab6 100644 --- a/src/SIL.LCModel.Utils/MiscUtils.cs +++ b/src/SIL.LCModel.Utils/MiscUtils.cs @@ -122,9 +122,11 @@ public static byte[] ReplaceSubArray(this byte[] input, int start, int length, b /// ------------------------------------------------------------------------------------ public static int CompareHex(string sx, string sy) { - if (sx != null && sx.StartsWith("0x", true, CultureInfo.InvariantCulture)) + if (sx == null) throw new ArgumentNullException(nameof(sx)); + if (sy == null) throw new ArgumentNullException(nameof(sy)); + if (sx.StartsWith("0x", true, CultureInfo.InvariantCulture)) sx = sx.Substring(2); - if (sy != null && sy.StartsWith("0x", true, CultureInfo.InvariantCulture)) + if (sy.StartsWith("0x", true, CultureInfo.InvariantCulture)) sy = sy.Substring(2); int x = (sx == String.Empty) ? 0 : int.Parse(sx, NumberStyles.HexNumber, null); diff --git a/src/SIL.LCModel.Utils/ReflectionHelper.cs b/src/SIL.LCModel.Utils/ReflectionHelper.cs index 83051907..27583be2 100644 --- a/src/SIL.LCModel.Utils/ReflectionHelper.cs +++ b/src/SIL.LCModel.Utils/ReflectionHelper.cs @@ -100,7 +100,10 @@ static public Object CreateObject(string assemblyName, string className1, { Assembly assembly; string location = Assembly.GetExecutingAssembly().Location; - string assemblyPath = Path.Combine(Path.GetDirectoryName(location), assemblyName); + var directoryName = Path.GetDirectoryName(location); + if (directoryName == null) + throw new InvalidOperationException("Could not get directory name from location " + location); + string assemblyPath = Path.Combine(directoryName, assemblyName); try { assembly = Assembly.LoadFrom(assemblyPath); @@ -183,7 +186,10 @@ static public object CallStaticMethod(string assemblyName, string className1, public static Type GetType(string assemblyName, string className1) { Assembly assembly; - string baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(Environment.OSVersion.Platform == PlatformID.Unix ? 5 : 6); + var codeBase = Assembly.GetExecutingAssembly().CodeBase; + string baseDir = Path.GetDirectoryName(codeBase)?.Substring(Environment.OSVersion.Platform == PlatformID.Unix ? 5 : 6); + if (baseDir == null) + throw new InvalidOperationException("Could not get assembly base directory from CodeBase " + codeBase); string assemblyPath = Path.Combine(baseDir, assemblyName); try { @@ -448,7 +454,7 @@ private static object Invoke(object binding, string name, object[] args, Binding // If necessary, go up the inheritance chain until the name // of the method, property or field is found. - Type type = (binding is Type ? binding as Type : binding.GetType()); + Type type = binding as Type ?? binding.GetType(); // TODO-Linux: System.Boolean System.Type::op_Inequality(System.Type,System.Type) // is marked with [MonoTODO] and might not work as expected in 4.0. while (type.GetMember(name, flags).Length == 0 && type.BaseType != null) diff --git a/src/SIL.LCModel.Utils/RegistryHelper.cs b/src/SIL.LCModel.Utils/RegistryHelper.cs index 43d8e1a1..2057d247 100644 --- a/src/SIL.LCModel.Utils/RegistryHelper.cs +++ b/src/SIL.LCModel.Utils/RegistryHelper.cs @@ -45,7 +45,8 @@ public static RegistryKey CompanyKey { using (var softwareKey = Registry.CurrentUser.CreateSubKey("Software")) { - Debug.Assert(softwareKey != null); + if (softwareKey == null) + throw new InvalidOperationException("Could not open HKCU\\Software"); return softwareKey.CreateSubKey(CompanyName); } } @@ -71,7 +72,8 @@ public static RegistryKey CompanyKeyLocalMachine { using (var softwareKey = Registry.LocalMachine.OpenSubKey("Software")) { - Debug.Assert(softwareKey != null); + if (softwareKey == null) + throw new InvalidOperationException("Could not open HKLM\\Software"); return softwareKey.OpenSubKey(CompanyName); } } @@ -97,7 +99,8 @@ public static RegistryKey CompanyKeyLocalMachineForWriting { using (var softwareKey = Registry.LocalMachine.CreateSubKey("Software")) { - Debug.Assert(softwareKey != null); + if (softwareKey == null) + throw new InvalidOperationException("Could not open HKLM\\Software"); return softwareKey.CreateSubKey(CompanyName); } } @@ -149,7 +152,8 @@ public static bool RegEntryValueExists(RegistryKey key, string subKey, string re using (var regSubKey = key.OpenSubKey(subKey)) { - Debug.Assert(regSubKey != null, "Should have caught this in the KeyExists call above"); + if (regSubKey == null) + throw new InvalidOperationException("Could not open subkey"); if (Array.IndexOf(regSubKey.GetValueNames(), regEntry) >= 0) { value = regSubKey.GetValue(regEntry); diff --git a/src/SIL.LCModel.Utils/SimpleBag.cs b/src/SIL.LCModel.Utils/SimpleBag.cs index 891686eb..5c332602 100644 --- a/src/SIL.LCModel.Utils/SimpleBag.cs +++ b/src/SIL.LCModel.Utils/SimpleBag.cs @@ -108,10 +108,10 @@ public int Count { if (m_contents is T) return 1; - if (m_contents is ConcurrentDictionary) + if (m_contents is ConcurrentDictionary dict) { int result = 0; - foreach (var kvp in (m_contents as ConcurrentDictionary)) + foreach (var kvp in dict) { result += kvp.Value; } @@ -133,10 +133,10 @@ public int Occurrences(T item) return 1; else return 0; - if (m_contents is ConcurrentDictionary) + if (m_contents is ConcurrentDictionary dict) { int result; - (m_contents as ConcurrentDictionary).TryGetValue(item, out result); + dict.TryGetValue(item, out result); return result; } return 0; @@ -166,9 +166,9 @@ public IEnumerator GetEnumerator() { if (m_contents is T) yield return (T)m_contents; - if (m_contents is ConcurrentDictionary) + if (m_contents is ConcurrentDictionary dict) { - foreach (var kvp in (m_contents as ConcurrentDictionary)) + foreach (var kvp in dict) { for (int i = 0; i < kvp.Value; i++) yield return kvp.Key; diff --git a/src/SIL.LCModel.Utils/StringUtils.cs b/src/SIL.LCModel.Utils/StringUtils.cs index 08f4f996..79504bf9 100644 --- a/src/SIL.LCModel.Utils/StringUtils.cs +++ b/src/SIL.LCModel.Utils/StringUtils.cs @@ -389,18 +389,16 @@ public static string GetUnicodeValueString(int codepoint) /// ------------------------------------------------------------------------------------ public static int FirstDiff(string first, string second) { - int lenFirst = 0; - if (first != null) - lenFirst = first.Length; - int lenSecond = 0; - if (second != null) - lenSecond = second.Length; - int lenBoth = Math.Min(lenFirst, lenSecond); + if (first == second) + return -1; + if (first == null || second == null) + return 0; + int lenBoth = Math.Min(first.Length, second.Length); for (int ich = 0; ich < lenBoth; ich++) if (first[ich] != second[ich]) return ich; // equal as far as len. - if (lenFirst != lenSecond) + if (first.Length != second.Length) return lenBoth; return -1; } @@ -414,12 +412,13 @@ public static int FirstDiff(string first, string second) /// ------------------------------------------------------------------------------------ public static int LastDiff(string first, string second) { - int lenFirst = 0; - if (first != null) - lenFirst = first.Length; - int lenSecond = 0; - if (second != null) - lenSecond = second.Length; + if (first == second) + return -1; + if (first == null || second == null) + return 0; + + var lenFirst = first.Length; + var lenSecond = second.Length; int diffLen = lenFirst - lenSecond; // how much first is longer; what to add to position in first for corresponding in second. int ichEnd = Math.Max(diffLen, 0); diff --git a/src/SIL.LCModel/Application/ApplicationServices/SingleLexReference.cs b/src/SIL.LCModel/Application/ApplicationServices/SingleLexReference.cs index fbc3c9fd..0f07fcac 100644 --- a/src/SIL.LCModel/Application/ApplicationServices/SingleLexReference.cs +++ b/src/SIL.LCModel/Application/ApplicationServices/SingleLexReference.cs @@ -73,7 +73,7 @@ public int MappingType { if (m_nMappingType < 0) { - var lrt = m_lexRef.Owner as ILexRefType; + var lrt = (ILexRefType)m_lexRef.Owner; m_nMappingType = lrt.MappingType; } return m_nMappingType; @@ -202,13 +202,13 @@ private void GetOwnerAndWsCode(int ws, out ILexRefType lrtOwner, out SpecialWrit /// public string CrossReference(int ws) { - if (CrossRefObject is ILexEntry) + if (CrossRefObject is ILexEntry e) { - return (CrossRefObject as ILexEntry).HeadWordForWs(ws).Text; + return e.HeadWordForWs(ws).Text; } - else if (CrossRefObject is ILexSense) + else if (CrossRefObject is ILexSense s) { - return (CrossRefObject as ILexSense).OwnerOutlineNameForWs(ws).Text; + return s.OwnerOutlineNameForWs(ws).Text; } else { @@ -223,9 +223,8 @@ public string CrossReference(int ws) /// public string CrossReferenceGloss(int ws) { - if (CrossRefObject is ILexEntry) + if (CrossRefObject is ILexEntry le) { - var le = CrossRefObject as ILexEntry; if (le.SensesOS.Count > 0) { return le.SensesOS[0].Gloss.get_String(ws).Text; @@ -235,9 +234,9 @@ public string CrossReferenceGloss(int ws) return ""; } } - else if (CrossRefObject is ILexSense) + else if (CrossRefObject is ILexSense s) { - return (CrossRefObject as ILexSense).Gloss.get_String(ws).Text; + return s.Gloss.get_String(ws).Text; } else { @@ -273,9 +272,9 @@ public string RefLIFTid { get { - return CrossRefObject is ILexEntry - ? (CrossRefObject as ILexEntry).LIFTid - : (CrossRefObject is ILexSense ? (CrossRefObject as ILexSense).LIFTid : "???"); + return CrossRefObject is ILexEntry e + ? e.LIFTid + : (CrossRefObject is ILexSense sense ? sense.LIFTid : "???"); } } diff --git a/src/SIL.LCModel/Application/ApplicationServices/XmlImportData.cs b/src/SIL.LCModel/Application/ApplicationServices/XmlImportData.cs index 93af69c4..a19eb7ac 100644 --- a/src/SIL.LCModel/Application/ApplicationServices/XmlImportData.cs +++ b/src/SIL.LCModel/Application/ApplicationServices/XmlImportData.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; using System.Text; using System.Xml; @@ -100,8 +101,8 @@ internal PendingLink(FieldInfo fi, XmlReader xrdr, string linkAttribute) m_fi = fi; m_sName = xrdr.Name; m_sState = xrdr.ReadState.ToString(); - if (xrdr is IXmlLineInfo) - m_line = (xrdr as IXmlLineInfo).LineNumber; + if (xrdr is IXmlLineInfo info) + m_line = info.LineNumber; else m_line = 0; if (linkAttribute != null) @@ -256,7 +257,7 @@ private void LogMessage(string sMsg) { Debug.Assert(m_wrtrLog != null); Debug.Assert(!string.IsNullOrEmpty(sMsg)); - m_wrtrLog.WriteLine(sMsg); + m_wrtrLog?.WriteLine(sMsg); } /// ------------------------------------------------------------------------------------ @@ -394,9 +395,8 @@ private IMoMorphSynAnalysis GetEmptyMsa(ILexEntry le) { foreach (IMoMorphSynAnalysis msa in le.MorphoSyntaxAnalysesOC) { - if (msa is IMoUnclassifiedAffixMsa) + if (msa is IMoUnclassifiedAffixMsa msaUncl) { - IMoUnclassifiedAffixMsa msaUncl = msa as IMoUnclassifiedAffixMsa; if (msaUncl.PartOfSpeechRA == null && msaUncl.ComponentsRS.Count == 0 && msaUncl.GlossBundleRS.Count == 0 && @@ -406,8 +406,7 @@ private IMoMorphSynAnalysis GetEmptyMsa(ILexEntry le) } } } - if (m_factUnclAffMsa == null) - m_factUnclAffMsa = m_cache.ServiceLocator.GetInstance(); + m_factUnclAffMsa ??= m_cache.ServiceLocator.GetInstance(); IMoUnclassifiedAffixMsa msaT = m_factUnclAffMsa.Create(); le.MorphoSyntaxAnalysesOC.Add(msaT); return msaT; @@ -416,9 +415,8 @@ private IMoMorphSynAnalysis GetEmptyMsa(ILexEntry le) { foreach (IMoMorphSynAnalysis msa in le.MorphoSyntaxAnalysesOC) { - if (msa is IMoStemMsa) + if (msa is IMoStemMsa msaStem) { - IMoStemMsa msaStem = msa as IMoStemMsa; if (msaStem.PartOfSpeechRA == null && msaStem.ComponentsRS.Count == 0 && msaStem.GlossBundleRS.Count == 0 && @@ -590,9 +588,9 @@ private void CopyCustomFieldData(ICmObject cmoOld, ICmObject cmoNew) { Debug.Assert(cmoOld.ClassID == cmoNew.ClassID); IFwMetaDataCacheManaged mdc = m_cache.MetaDataCache as IFwMetaDataCacheManaged; - Debug.Assert(mdc != null); + if (mdc == null) throw new Exception("Cannot cast MetaDataCache to IFwMetaDataCacheManaged"); ISilDataAccessManaged sda = m_cache.DomainDataByFlid as ISilDataAccessManaged; - Debug.Assert(sda != null); + if (sda == null) throw new Exception("Cannot cast DomainDataByFlid to ISilDataAccessManaged"); foreach (int flid in mdc.GetFields(cmoOld.ClassID, true, (int)CellarPropertyTypeFilter.All)) { if (!mdc.IsCustom(flid)) @@ -1005,7 +1003,7 @@ private void ReadXmlObject(XmlReader xrdr, FieldInfo fi, ICmObject objToUse) else cmo = factory.Create(guid, (IPhPhonemeSet)fi.Owner); // Remove the default code added by PhTerminalUnit.SetDefaultValuesAfterInit in OverridesLing_Lex. - (cmo as PhBdryMarker).CodesOS.Clear(); + (cmo as PhBdryMarker)?.CodesOS.Clear(); break; case "PhPhonData": cmo = m_cache.LangProject.PhonologicalDataOA; @@ -1110,7 +1108,7 @@ private void ReadXmlObject(XmlReader xrdr, FieldInfo fi, ICmObject objToUse) } if (!String.IsNullOrEmpty(sId)) { - m_mapIdGuid.Add(sId, cmo.Guid); + m_mapIdGuid.Add(sId, cmo!.Guid); m_mapGuidId.Add(cmo.Guid, sId); } if (m_phonology) @@ -1139,7 +1137,7 @@ private void ReadXmlObject(XmlReader xrdr, FieldInfo fi, ICmObject objToUse) { if (m_mapFormEntry == null) FillEntryMap(); - ILexEntry le = cmo as ILexEntry; + ILexEntry le = (ILexEntry)cmo; ILexEntry leDup; StoreEntryInMap(le, fNewObject, true, out leDup); if (leDup != null) @@ -1315,7 +1313,7 @@ private void ReadXmlFields(XmlReader xrdr, ICmObject cmoOwner, bool fOwnerIsNew, FieldInfo fiBack = fiParent; while (fiBack != null && fiBack.Owner != realOwner) fiBack = fiBack.ParentOfOwner; - if (fiBack.Owner == realOwner) + if (fiBack != null && fiBack.Owner == realOwner) fi = new FieldInfo(realOwner, flid, cpt, fiBack.OwnerIsNew, fiBack.ParentOfOwner); } else @@ -1410,7 +1408,7 @@ private void ReadXmlFields(XmlReader xrdr, ICmObject cmoOwner, bool fOwnerIsNew, if (flid == StTxtParaTags.kflidSegments) { IStTxtPara para = cmoOwner as IStTxtPara; - Debug.Assert(para != null); + if (para == null) throw new NullReferenceException("cmoOwner as IStTxtPara"); int i = 0; do { @@ -1455,11 +1453,11 @@ private void ReadXmlFields(XmlReader xrdr, ICmObject cmoOwner, bool fOwnerIsNew, s = s.Replace("\r\n", "\n"); s = s.Replace('\r', '\n'); s = s.Replace('\n', StringUtils.kChHardLB); - if (fi.Owner is ILexEntry) + if (fi?.Owner is ILexEntry) { AppendMessageToImportResidue(fi.Owner, s, m_cache.DefaultUserWs); } - else if (fi.Owner is ILexSense) + else if (fi?.Owner is ILexSense) { // Review gjm: Why do we do nothing in this case?! (we could replace all this // if - else if stuff with the one "AppendMessage..." line. @@ -2272,7 +2270,7 @@ private void FixPendingLinks() } if (fJoinWithPrev) { - if (!lrPrev.TargetsRS.Contains(cmoTarget)) + if (lrPrev != null && !lrPrev.TargetsRS.Contains(cmoTarget)) lrPrev.TargetsRS.Add(cmoTarget); } else @@ -2900,6 +2898,7 @@ private void EnsureLrtMapsFilled() } } + [MemberNotNull(nameof(m_mapFormEntry))] private void FillEntryMap() { if (m_mapFormEntry == null) @@ -3278,6 +3277,7 @@ private int GetMediaFile(string sPath, PendingLink pend) return file.Hvo; } + [MemberNotNull(nameof(m_mapPathMediaFile))] private void CreatePathMediaFileMap() { m_mapPathMediaFile = new Dictionary(); @@ -3304,7 +3304,7 @@ private int GetPictureFile(string sPath, PendingLink pend) if (m_mapPathPictureFile == null) CreatePathPictureFileMap(); int hvo; - if (m_mapPathPictureFile.TryGetValue(sPath, out hvo)) + if (m_mapPathPictureFile!.TryGetValue(sPath, out hvo)) return hvo; ICmFolder folder = GetDesiredCmFolder("Local Pictures", m_cache.LangProject.PicturesOC); if (m_factCmFile == null) @@ -3438,6 +3438,7 @@ private IReversalIndexEntry GetMatchingReversalEntry(int wsHvo, string sForm) return rie; } + [MemberNotNull(nameof(m_mapFormReversal))] private void CreateFormReversalMap() { m_mapFormReversal = new Dictionary(); diff --git a/src/SIL.LCModel/Application/ApplicationServices/XmlList.cs b/src/SIL.LCModel/Application/ApplicationServices/XmlList.cs index 5c12e90d..d8771dc8 100644 --- a/src/SIL.LCModel/Application/ApplicationServices/XmlList.cs +++ b/src/SIL.LCModel/Application/ApplicationServices/XmlList.cs @@ -18,6 +18,7 @@ using SIL.LCModel.Core.KernelInterfaces; using SIL.LCModel.Core.Text; using SIL.LCModel.Infrastructure; +using SIL.LCModel.Tools; using SIL.LCModel.Utils; namespace SIL.LCModel.Application.ApplicationServices @@ -271,14 +272,14 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl // Additional CmSemanticDomain fields. case "LouwNidaCodes": - if (poss is ICmSemanticDomain) - (poss as ICmSemanticDomain).LouwNidaCodes = ReadUnicodeFromXml(xrdrSub); + if (poss is ICmSemanticDomain domain) + domain.LouwNidaCodes = ReadUnicodeFromXml(xrdrSub); else SkipAndReportUnexpectedElement(xrdrSub); break; case "OcmCodes": - if (poss is ICmSemanticDomain) - (poss as ICmSemanticDomain).OcmCodes = ReadUnicodeFromXml(xrdrSub); + if (poss is ICmSemanticDomain domain1) + domain1.OcmCodes = ReadUnicodeFromXml(xrdrSub); else SkipAndReportUnexpectedElement(xrdrSub); break; @@ -297,8 +298,8 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl // Additional PartOfSpeech fields. case "CatalogSourceId": - if (poss is IPartOfSpeech) - (poss as IPartOfSpeech).CatalogSourceId = ReadUnicodeFromXml(xrdrSub); + if (poss is IPartOfSpeech speech) + speech.CatalogSourceId = ReadUnicodeFromXml(xrdrSub); else SkipAndReportUnexpectedElement(xrdrSub); break; @@ -424,6 +425,8 @@ private void ReadDomainQuestion(XmlReader xrdrSub, ICmSemanticDomain dom) private void LoadRelatedDomainsFromXml(XmlReader xrdr, ICmSemanticDomain dom) { Debug.Assert(dom != null); + if (dom == null) + throw new NullReferenceException("ICmSemanticDomain dom cannot be null"); if (xrdr.ReadToDescendant("Link")) { do diff --git a/src/SIL.LCModel/Application/ApplicationServices/XmlTranslatedLists.cs b/src/SIL.LCModel/Application/ApplicationServices/XmlTranslatedLists.cs index 90ce16eb..76906e43 100644 --- a/src/SIL.LCModel/Application/ApplicationServices/XmlTranslatedLists.cs +++ b/src/SIL.LCModel/Application/ApplicationServices/XmlTranslatedLists.cs @@ -382,7 +382,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl { using (var xrdrT = XmlReader.Create(srdr)) { - SetMultiUnicodeFromXml(xrdrT, (poss as ICmPerson).Alias); + SetMultiUnicodeFromXml(xrdrT, ((ICmPerson)poss).Alias); xrdrT.Close(); } } @@ -393,7 +393,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl { using (var xrdrT = XmlReader.Create(srdr)) { - SetMultiUnicodeFromXml(xrdrT, (poss as ICmLocation).Alias); + SetMultiUnicodeFromXml(xrdrT, ((ICmLocation)poss).Alias); xrdrT.Close(); } } @@ -412,7 +412,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl { using (var xrdrT = XmlReader.Create(srdr)) { - SetMultiUnicodeFromXml(xrdrT, (poss as ILexEntryType).ReverseAbbr); + SetMultiUnicodeFromXml(xrdrT, ((ILexEntryType)poss).ReverseAbbr); xrdrT.Close(); } } @@ -431,7 +431,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl { using (var xrdrT = XmlReader.Create(srdr)) { - SetMultiUnicodeFromXml(xrdrT, (poss as ILexRefType).ReverseAbbreviation); + SetMultiUnicodeFromXml(xrdrT, ((ILexRefType)poss).ReverseAbbreviation); xrdrT.Close(); } } @@ -450,7 +450,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl { using (var xrdrT = XmlReader.Create(srdr)) { - SetMultiUnicodeFromXml(xrdrT, (poss as ILexRefType).ReverseName); + SetMultiUnicodeFromXml(xrdrT, ((ILexRefType)poss).ReverseName); xrdrT.Close(); } } @@ -507,9 +507,9 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl case "Alias": if (poss is ICmPerson) - SetMultiUnicodeFromXml(xrdrSub, (poss as ICmPerson).Alias); + SetMultiUnicodeFromXml(xrdrSub, ((ICmPerson)poss).Alias); else if (poss is ICmLocation) - SetMultiUnicodeFromXml(xrdrSub, (poss as ICmLocation).Alias); + SetMultiUnicodeFromXml(xrdrSub, ((ICmLocation)poss).Alias); else if (poss == null) aliasXml = GetXmlOfElement(xrdrSub); else @@ -518,7 +518,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl case "ReverseAbbr": if (poss is ILexEntryType) - SetMultiUnicodeFromXml(xrdrSub, (poss as ILexEntryType).ReverseAbbr); + SetMultiUnicodeFromXml(xrdrSub, ((ILexEntryType)poss).ReverseAbbr); else if (poss == null) revabbrXml = GetXmlOfElement(xrdrSub); else @@ -527,7 +527,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl case "ReverseAbbreviation": if (poss is ILexRefType) - SetMultiUnicodeFromXml(xrdrSub, (poss as ILexRefType).ReverseAbbreviation); + SetMultiUnicodeFromXml(xrdrSub, ((ILexRefType)poss).ReverseAbbreviation); else if (poss == null) revabbrevXml = GetXmlOfElement(xrdrSub); else @@ -536,7 +536,7 @@ private void ReadPossItem(XmlReader xrdrSub, ICmPossibility poss, string sItemCl case "ReverseName": if (poss is ILexRefType) - SetMultiUnicodeFromXml(xrdrSub, (poss as ILexRefType).ReverseName); + SetMultiUnicodeFromXml(xrdrSub, ((ILexRefType)poss).ReverseName); else if (poss == null) revnameXml = GetXmlOfElement(xrdrSub); else diff --git a/src/SIL.LCModel/Application/DomainDataByFlidDecoratorBase.cs b/src/SIL.LCModel/Application/DomainDataByFlidDecoratorBase.cs index b8541225..7ed36641 100644 --- a/src/SIL.LCModel/Application/DomainDataByFlidDecoratorBase.cs +++ b/src/SIL.LCModel/Application/DomainDataByFlidDecoratorBase.cs @@ -1033,8 +1033,8 @@ public override IFwMetaDataCache MetaDataCache public void SetOverrideMdc(IFwMetaDataCacheManaged mdc) { m_mdc = mdc; - if (m_domainDataByFlid is DomainDataByFlidDecoratorBase) - (m_domainDataByFlid as DomainDataByFlidDecoratorBase).SetOverrideMdc(mdc); + if (m_domainDataByFlid is DomainDataByFlidDecoratorBase @base) + @base.SetOverrideMdc(mdc); } /// Member GetOutlineNumber diff --git a/src/SIL.LCModel/DomainImpl/AnalysisAdjuster.cs b/src/SIL.LCModel/DomainImpl/AnalysisAdjuster.cs index 1b0d359a..e571b889 100644 --- a/src/SIL.LCModel/DomainImpl/AnalysisAdjuster.cs +++ b/src/SIL.LCModel/DomainImpl/AnalysisAdjuster.cs @@ -120,7 +120,7 @@ internal sealed class AnalysisAdjuster private Dictionary m_finalEndIndexAdjustments; private List m_segsToMove; // In HandleMoveDest, the segments to move entirely to the destination. - // In HandleMoveDest, the analyses to move to the destination (from the incompletely moved seg). + // In HandleMoveDest, the analyses to move to the destination (from the incompletely moved seg). private List m_analysesToMove; private ISegment m_segPartlyMoved; // the sourceof m_analysesToMove, if any incomplete segment overlaps the move. private bool m_changedFontOnly; @@ -134,12 +134,12 @@ internal sealed class AnalysisAdjuster private void PrintDebugInfo() { Debug.Print("************Begin Offsets********************"); - if(m_oldContents != null) + if (m_oldContents != null) { Debug.Print("oldContents string:"); PrintOffsetLines(m_oldContents.Text, m_oldBeginOffsets, m_oldEndOffsets); } - if(m_newContents != null) + if (m_newContents != null) { Debug.Print("newContents string:"); PrintOffsetLines(m_newContents.Text, m_newBeginOffsets, null); @@ -193,7 +193,7 @@ private static void PrintOffsetLines(string text, int[] begin, int[] end) { Debug.Print(text); PrintOneOffsetLine(text, begin, ": begin offsets"); - if(end != null) + if (end != null) PrintOneOffsetLine(text, end, ": end offsets"); } @@ -227,7 +227,7 @@ private AnalysisAdjuster(IStTxtPara para, ITsString oldContents, TsStringDiffInf m_oldContents = oldContents; m_newContents = m_para.Contents; m_changedFontOnly = false; - if(diffInfo != null && ( diffInfo.IchFirstDiff != 0 || diffInfo.CchDeleteFromOld != diffInfo.CchInsert || + if (diffInfo != null && (diffInfo.IchFirstDiff != 0 || diffInfo.CchDeleteFromOld != diffInfo.CchInsert || m_oldContents == null || m_newContents == null || m_oldContents.Length == 0 || !m_oldContents.GetChars(0, m_oldContents.Length).Equals(m_newContents.GetChars(0, m_newContents.Length)))) { @@ -243,7 +243,7 @@ private AnalysisAdjuster(IStTxtPara para, ITsString oldContents, TsStringDiffInf } /// for tests - internal AnalysisAdjuster() {} + internal AnalysisAdjuster() { } #endregion #region Public methods @@ -527,7 +527,7 @@ private void UpdateAffectedReferences() { var endSeg = iar.EndRef().Segment; var begSeg = iar.BegRef().Segment; - if(begSeg == null || endSeg == null) + if (begSeg == null || endSeg == null) { var logString = String.Format("Found a corrupt IAnalysisReference when trying to update and adjust. Removed the reference with GUID {0}", iar.Guid); @@ -540,7 +540,7 @@ private void UpdateAffectedReferences() var iendSeg = endSeg.IndexInOwner; if (iendSeg < m_iSegFirstModified || (iendSeg == m_iSegFirstModified && iend < m_iFirstAnalysisToFix)) - continue; // The whole IAnalysisReference is before the change, so no change. + continue; // The whole IAnalysisReference is before the change, so no change. var ifirstAnalysisInSegToFix = 0; var ibeg = iar.BegRef().Index; var ibegSeg = begSeg.IndexInOwner; @@ -560,7 +560,7 @@ private void UpdateAffectedReferences() // BegRef section if (ibegSeg >= m_iSegFirstModified && ibeg >= ifirstAnalysisInSegToFix) { - if(CheckForDeleteableIAR(iar, ifirstAnalysisInSegToFix, m_cRemovedAnalyses, m_cAddedAnalyses)) + if (CheckForDeleteableIAR(iar, ifirstAnalysisInSegToFix, m_cRemovedAnalyses, m_cAddedAnalyses)) { refsToDelete.Add(iar); continue; @@ -733,12 +733,12 @@ private void DeleteReferences(IEnumerable iarList) { if (iar is ITextTag) { - var owner = iar.Owner as IStText; + var owner = (IStText)iar.Owner; owner.TagsOC.Remove(iar as ITextTag); } else { - var owner = iar.Owner as IConstChartRow; + var owner = (IConstChartRow)iar.Owner; owner.CellsOS.Remove(iar as IConstituentChartCellPart); } m_oldParaRefs.Remove(iar); @@ -843,7 +843,7 @@ private void DiscardDeletedSegments() if (punctTsStr.Length > 0) { IPunctuationForm pf = WfiWordformServices.FindOrCreatePunctuationform(m_para.Cache, punctTsStr); - m_punctRemainingFromLastDeletedSegment = new List {pf}; + m_punctRemainingFromLastDeletedSegment = new List { pf }; } } } @@ -901,7 +901,7 @@ private void FixHangingReferences(int iFirstSegmentSurviving, int cOldAnalyses) // which can bring it about. It's no good 'correcting' the index to something still invalid, // so if that is what we're about to do, we delete it instead, as unrepairable. // Eventually we may figure out something better to do. - if(iar.BegRef().Index + cOldAnalyses < 0 || iar.BegRef().Index + cOldAnalyses < 0) + if (iar.BegRef().Index + cOldAnalyses < 0 || iar.BegRef().Index + cOldAnalyses < 0) { DiscardDeletedRefs(newSeg); //It should be gone, we can't fix it, get rid of it. continue; @@ -949,7 +949,7 @@ private void FixHangingReferences(int iFirstSegmentSurviving, int cOldAnalyses) newSeg = m_para.SegmentsOS[iFirstSegmentSurviving - 1]; // Get segment before deleted one cNewAnalyses = newSeg.AnalysesRS.Count; iar.ChangeToDifferentSegment(newSeg, false, true); - if(cOldAnalyses > 0 && cNewAnalyses > cOldAnalyses) + if (cOldAnalyses > 0 && cNewAnalyses > cOldAnalyses) { // A segment break was deleted (i.e. two segments merged); we will try to preserve // the index position in the new (combined) segment. @@ -1010,7 +1010,7 @@ private void DiscardDeletedRefs(ISegment seg) private static void DeleteChartRefs(IEnumerable cellList) { foreach (var cellPart in cellList) - ((IConstChartRow) cellPart.Owner).CellsOS.Remove(cellPart); + ((IConstChartRow)cellPart.Owner).CellsOS.Remove(cellPart); } private void DeleteTextTags(IEnumerable tagList) @@ -1153,7 +1153,7 @@ void AnalyzeNewText() if (ichStartWordBL == m_baseline.Length) break; var token = m_baseline.Substring(ichStartWordBL, ichEndWordBL - ichStartWordBL); // wordform or punct - //Debug.Assert(startWord < endWord); + //Debug.Assert(startWord < endWord); if (ichStartWordBL >= ichLimSegBL) { isegment++; @@ -1260,7 +1260,7 @@ private void GetNewAnalysisGroups() iLastAnalysisToFix = GetLastAnalysisToFix(out iTokenIndex); } else - { // if the font changed, but text did not change, we want the wordform analyses to be completely replaced, + { // if the font changed, but text did not change, we want the wordform analyses to be completely replaced, // but the segment annotations to remain. GetLastAnalysisToFix was retaining some of the old // analyses (typically a wordform and end punctuation). Later this causes problems in // OverridesCellar ParsedParagraphOffsetsMethod.AdvancePastWord() which returns 0 for the @@ -1448,7 +1448,7 @@ private void DetermineWhatToMove(int ichSource, int cchInsert, IStTxtPara source // Find entire segments to move. m_segsToMove = new List(); m_segPartlyMoved = null; - foreach(ISegment seg in source.SegmentsOS) + foreach (ISegment seg in source.SegmentsOS) { if (seg.BeginOffset >= ichSource) m_segsToMove.Add(seg); @@ -1509,7 +1509,7 @@ private List MoveAnalysisAndReferencesFromOldPara(int cchIns private List MoveReferencesFromOldPara(ISegment newSeg, int canalysesLeftBehind) { - Debug.Assert(m_segPartlyMoved != null, "Nothing to do! I shouldn't have been called."); + if (m_segPartlyMoved == null) throw new NullReferenceException("m_segPartlyMoved"); var refsMoved = new List(); var oldPara = (IStTxtPara)m_segPartlyMoved.Owner; var oldReferences = oldPara.GetTags().Cast().ToList(); diff --git a/src/SIL.LCModel/DomainImpl/CmCell.cs b/src/SIL.LCModel/DomainImpl/CmCell.cs index ade5dbba..981f23b6 100644 --- a/src/SIL.LCModel/DomainImpl/CmCell.cs +++ b/src/SIL.LCModel/DomainImpl/CmCell.cs @@ -258,8 +258,9 @@ public bool MatchesCriteria(int[] val) return (val.Length == 0 && m_matchEmpty); case ComparisonTypes.kMatches: - Debug.Assert(m_matchValues != null, - "Illegal to call MatchesCriteria without first setting a match values list"); + if (m_matchValues == null) + throw new NullReferenceException( + "Illegal to call MatchesCriteria without first setting a match values list"); foreach (int hvoRefObj in val) { if (m_matchValues.Contains(hvoRefObj)) diff --git a/src/SIL.LCModel/DomainImpl/CmObject.cs b/src/SIL.LCModel/DomainImpl/CmObject.cs index 9a02b923..9a6e5b3d 100644 --- a/src/SIL.LCModel/DomainImpl/CmObject.cs +++ b/src/SIL.LCModel/DomainImpl/CmObject.cs @@ -700,7 +700,7 @@ public void MergeObject(ICmObject objSrc) /// ------------------------------------------------------------------------------------ public virtual void MergeObject(ICmObject objSrc, bool fLoseNoStringData) { - Debug.Assert(m_cache != null); + if (m_cache == null) throw new NullReferenceException("m_cache"); // We don't allow merging items of different classes. Debug.Assert(ClassID == objSrc.ClassID); if (ClassID != objSrc.ClassID) @@ -807,7 +807,7 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString } } } - Object myCurrentValue = null; + Object myCurrentValue = new object(); MethodInfo mySetMethod = null; Object srcCurrentValue = null; @@ -841,7 +841,6 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString } if (srcCurrentValue == null) continue; // Nothing to merge. - Debug.Assert(srcCurrentValue != null); /* * NOTE: Each of the cases (except the exception, which can't be tested) @@ -972,7 +971,7 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString { if (MergeStringProp(flid, nType, objSrc, fLoseNoStringData, myCurrentValue, srcCurrentValue)) break; - var myMsa = myCurrentValue as IMultiStringAccessor; + var myMsa = (IMultiStringAccessor)myCurrentValue; myMsa.MergeAlternatives(srcCurrentValue as IMultiStringAccessor, fLoseNoStringData); break; } @@ -1008,7 +1007,7 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString { if (MergeStringProp(flid, nType, objSrc, fLoseNoStringData, myCurrentValue, srcCurrentValue)) break; - var myMua = myCurrentValue as IMultiUnicode; + var myMua = (IMultiUnicode)myCurrentValue; myMua.MergeAlternatives(srcCurrentValue as IMultiUnicode, fLoseNoStringData); break; } @@ -1021,9 +1020,10 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString var currentObj = myCurrentValue as ICmObject; if (myCurrentValue == null) { - if (nType == (int)CellarPropertyType.OwningAtomic || mySetMethod != null) + if (nType == (int)CellarPropertyType.OwningAtomic && + mySetMethod == null) throw new NullReferenceException("Method cannot be null for OwningAtomic type."); + if (mySetMethod != null) { - Debug.Assert(mySetMethod != null); mySetMethod.Invoke(this, new object[] { srcObj }); } else @@ -1035,7 +1035,7 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString // TODO-Linux: System.Boolean System.Type::op_Equality(System.Type,System.Type) // is marked with [MonoTODO] and might not work as expected in 4.0. else if (fLoseNoStringData && nType == (int)CellarPropertyType.OwningAtomic && srcObj != null - && currentObj.GetType() == srcObj.GetType()) + && currentObj?.GetType() == srcObj.GetType()) { // merge the child objects. currentObj.MergeObject(srcObj, true); @@ -1057,7 +1057,7 @@ public void MergeSelectedPropertiesOfObject(ICmObject objSrc, bool fLoseNoString } // Now move all incoming references. - var cmObject = ((CmObject)objSrc); + var cmObject = (CmObject)objSrc; cmObject.EnsureCompleteIncomingRefs(); ReplaceIncomingReferences(objSrc); if (objSrc.IsValidObject) // possibly side effects of ReplaceIncomingReferences will have deleted it already. diff --git a/src/SIL.LCModel/DomainImpl/CmPicture.cs b/src/SIL.LCModel/DomainImpl/CmPicture.cs index ba01d342..9f5a5b2a 100644 --- a/src/SIL.LCModel/DomainImpl/CmPicture.cs +++ b/src/SIL.LCModel/DomainImpl/CmPicture.cs @@ -328,7 +328,7 @@ public ITsString SenseNumberTSS } else { - sNumber = (Owner as LexSense).SenseNumber; + sNumber = ((LexSense)Owner).SenseNumber; } return m_cache.MakeUserTss(sNumber); } diff --git a/src/SIL.LCModel/DomainImpl/CmTranslation.cs b/src/SIL.LCModel/DomainImpl/CmTranslation.cs index e5befb50..8a50f9e3 100644 --- a/src/SIL.LCModel/DomainImpl/CmTranslation.cs +++ b/src/SIL.LCModel/DomainImpl/CmTranslation.cs @@ -33,7 +33,7 @@ partial void ValidateTypeRA(ref ICmPossibility newObjValue) // This check only applies if the translation belongs to a paragraph. if (Cache.FullyInitializedAndReadyToRock && Owner is IStTxtPara && - newObjValue.Guid != LangProjectTags.kguidTranBackTranslation) + newObjValue?.Guid != LangProjectTags.kguidTranBackTranslation) { throw new ArgumentException("Back translations are the only type of translation allowed for paragraphs"); } @@ -80,7 +80,7 @@ protected override void ITsStringAltChangedSideEffectsInternal(int multiAltFlid, TypeRA.Guid == CmPossibilityTags.kguidTranBackTranslation && ((originalValue == null && newValue != null) || (originalValue != null && newValue == null) || - (originalValue != null && originalValue.Text != newValue.Text))) + (originalValue != null && originalValue.Text != newValue?.Text))) { BtConverter.ConvertCmTransToInterlin(para, alternativeWs.Handle); MarkAsUnfinished(alternativeWs.Handle); diff --git a/src/SIL.LCModel/DomainImpl/FactoryAdditions.cs b/src/SIL.LCModel/DomainImpl/FactoryAdditions.cs index 11254e1b..b6c49a58 100644 --- a/src/SIL.LCModel/DomainImpl/FactoryAdditions.cs +++ b/src/SIL.LCModel/DomainImpl/FactoryAdditions.cs @@ -178,7 +178,7 @@ public int RDENewSense(int hvoDomain, List columns, ITsString[] rgtss) // create a LexSense that has the given definition and semantic domain // Needs to be LexSense, since later calls use non-interface methods. - LexSense ls = Create() as LexSense; + LexSense ls = (LexSense)Create(); le.SensesOS.Add(ls); #pragma warning disable 219 @@ -979,8 +979,8 @@ public ITextTag CreateOnText(AnalysisOccurrence begPoint, AnalysisOccurrence end throw new ArgumentException("Invalid begPoint."); if (endPoint == null || !endPoint.IsValid) throw new ArgumentException("Invalid endPoint."); - var txt = begPoint.Segment.Paragraph.Owner as IStText; - Debug.Assert(txt != null); + var txt = (IStText)begPoint.Segment.Paragraph.Owner; + // Debug.Assert(txt != null); var newby = Create(); txt.TagsOC.Add(newby); newby.BeginSegmentRA = begPoint.Segment; diff --git a/src/SIL.LCModel/DomainImpl/OverridesCellar.cs b/src/SIL.LCModel/DomainImpl/OverridesCellar.cs index 09412c53..0ad4c870 100644 --- a/src/SIL.LCModel/DomainImpl/OverridesCellar.cs +++ b/src/SIL.LCModel/DomainImpl/OverridesCellar.cs @@ -456,12 +456,12 @@ internal partial class CmAgentEvaluation { public bool Approves { - get { return (Owner as CmAgent).ApprovesOA == this; } + get { return (Owner as CmAgent)?.ApprovesOA == this; } } public bool Human { - get { return (Owner as CmAgent).Human; } + get { return (Owner as CmAgent)?.Human ?? false; } } } @@ -499,7 +499,7 @@ public void SetEvaluation(ICmObject target, Opinions opinion) DisapprovesOA = Services.GetInstance().Create(); if (ApprovesOA == null) ApprovesOA = Services.GetInstance().Create(); - var analysis = target as IWfiAnalysis; + var analysis = (IWfiAnalysis)target; if (opinion != Opinions.approves) analysis.EvaluationsRC.Remove(ApprovesOA); if (opinion != Opinions.disapproves) @@ -1972,10 +1972,10 @@ partial void InternalPathSideEffects(string originalValue, string newValue) var flid = m_cache.MetaDataCache.GetFieldId2(CmPictureTags.kClassId, "PathNameTSS", false); foreach (ICmPicture pict in m_cache.ServiceLocator.GetInstance().AllInstances()) { - if (pict.PictureFileRA == this) + if (pict.PictureFileRA == this && pict is CmPicture cmPicture) { ((IServiceLocatorInternal)m_cache.ServiceLocator).UnitOfWorkService.RegisterVirtualAsModified(pict, - flid, m_cache.MakeUserTss(""), (pict as CmPicture).PathNameTSS); + flid, m_cache.MakeUserTss(""), cmPicture.PathNameTSS); } } } @@ -2196,7 +2196,7 @@ public override bool IsEquivalent(IFsFeatureSpecification other) if (!base.IsEquivalent(other)) return false; - return (other as IFsClosedValue).ValueRA == ValueRA; + return (other as IFsClosedValue)?.ValueRA == ValueRA; } /// @@ -2430,10 +2430,12 @@ public override bool IsEquivalent(IFsFeatureSpecification other) if (!base.IsEquivalent(other)) return false; - var otherValue = (other as IFsComplexValue).ValueOA; + var otherValue = (other as IFsComplexValue)?.ValueOA; var thisValue = ValueOA; if (otherValue == null && thisValue == null) return true; + if (otherValue == null || thisValue == null) + return false; return otherValue.IsEquivalent(thisValue); } @@ -2545,7 +2547,7 @@ private string GetFeatureString(bool fLongForm) internal override void SetMoreCloneProperties(ICmObject clone) { IFsComplexValue val = (IFsComplexValue)clone; - val.ValueOA = (ValueOA as FsAbstractStructure).CreateNewObject(); + val.ValueOA = (ValueOA as FsAbstractStructure)?.CreateNewObject(); ValueOA.SetCloneProperties(val.ValueOA); } @@ -3003,22 +3005,22 @@ protected ISet GetFeatureList() switch (msa.ClassID) { case MoStemMsaTags.kClassId: - IMoStemMsa stemMsa = msa as IMoStemMsa; + IMoStemMsa stemMsa = (IMoStemMsa)msa; pos = stemMsa.PartOfSpeechRA; break; case MoInflAffMsaTags.kClassId: - IMoInflAffMsa inflMsa = msa as IMoInflAffMsa; + IMoInflAffMsa inflMsa = (IMoInflAffMsa)msa; pos = inflMsa.PartOfSpeechRA; break; case MoDerivAffMsaTags.kClassId: - IMoDerivAffMsa derivMsa = msa as IMoDerivAffMsa; + IMoDerivAffMsa derivMsa = (IMoDerivAffMsa)msa; if (derivMsa.FromProdRestrictRC.Contains((ICmPossibility)fs)) pos = derivMsa.FromPartOfSpeechRA; else pos = derivMsa.ToPartOfSpeechRA; break; case MoUnclassifiedAffixMsaTags.kClassId: - IMoUnclassifiedAffixMsa unclassMsa = msa as IMoUnclassifiedAffixMsa; + IMoUnclassifiedAffixMsa unclassMsa = (IMoUnclassifiedAffixMsa)msa; pos = unclassMsa.PartOfSpeechRA; break; } @@ -3174,7 +3176,7 @@ public override bool IsEquivalent(IFsFeatureSpecification other) if (!base.IsEquivalent(other)) return false; - return (other as IFsNegatedValue).ValueRA == ValueRA; + return (other as IFsNegatedValue)?.ValueRA == ValueRA; } /// @@ -3256,7 +3258,7 @@ public override bool IsEquivalent(IFsFeatureSpecification other) if (!base.IsEquivalent(other)) return false; - return (other as IFsDisjunctiveValue).ValueRC.IsEquivalent(ValueRC); + return (other as IFsDisjunctiveValue)?.ValueRC.IsEquivalent(ValueRC) ?? false; } /// @@ -3335,9 +3337,9 @@ public override bool IsEquivalent(IFsAbstractStructure other) if (!base.IsEquivalent(other)) return false; - var otherContents = (other as IFsFeatStrucDisj).ContentsOC; + var otherContents = (other as IFsFeatStrucDisj)?.ContentsOC; var thisContents = ContentsOC; - if (otherContents.Count != thisContents.Count) + if (otherContents?.Count != thisContents.Count) return false; foreach (var fsOther in otherContents) { @@ -3377,7 +3379,7 @@ internal override void CopyPropertiesTo(ICmObject clone) IFsFeatStrucDisj disj = (IFsFeatStrucDisj)clone; foreach (var oldFeat in ContentsOC) { - IFsFeatStruc newFeat = (oldFeat as FsFeatStruc).CreateNewObject() as IFsFeatStruc; + IFsFeatStruc newFeat = (oldFeat as FsFeatStruc)?.CreateNewObject() as IFsFeatStruc; disj.ContentsOC.Add(newFeat); oldFeat.SetCloneProperties(newFeat); } @@ -3643,7 +3645,7 @@ public void AddFeatureFromXml(XmlNode item, IFsFeatureSystem featsys) if (closedFeat != null) closedValue.FeatureRA = closedFeat; - var fsfv = closedFeat.GetOrCreateSymbolicValueFromXml(feature, item); + var fsfv = closedFeat?.GetOrCreateSymbolicValueFromXml(feature, item); if (fsfv != null) closedValue.ValueRA = fsfv; } @@ -3681,7 +3683,7 @@ public override bool IsEquivalent(IFsAbstractStructure other) return false; var fs = other as IFsFeatStruc; - if (fs.TypeRA != TypeRA) + if (fs?.TypeRA != TypeRA) return false; var otherFeatures = fs.FeatureSpecsOC; var thisFeatures = FeatureSpecsOC; @@ -3847,8 +3849,8 @@ public void PriorityUnion(IFsFeatStruc fsNew) { var commonFeatures = from newItem in fsNew.FeatureSpecsOC from myitem in FeatureSpecsOC - where (newItem is IFsClosedValue && (newItem as IFsClosedValue).FeatureRA.Name == myitem.FeatureRA.Name) || - (newItem is IFsComplexValue && (newItem as IFsComplexValue).FeatureRA.Name == myitem.FeatureRA.Name) + where (newItem is IFsClosedValue closed && closed.FeatureRA.Name == myitem.FeatureRA.Name) || + (newItem is IFsComplexValue complex && complex.FeatureRA.Name == myitem.FeatureRA.Name) select newItem; var nonCommonFeatures = from newItem in fsNew.FeatureSpecsOC where !commonFeatures.Contains(newItem) @@ -3868,16 +3870,11 @@ from myitem in FeatureSpecsOC } else { - var complex = myFeatureValues.First() as IFsComplexValue; - if (complex != null) + if (myFeatureValues.First() is IFsComplexValue complex && + spec is IFsComplexValue newComplexValue && + complex.ValueOA is IFsFeatStruc fs) { - var newComplexValue = spec as IFsComplexValue; - if (newComplexValue != null) - { - var fs = complex.ValueOA as IFsFeatStruc; - if (fs != null) - fs.PriorityUnion((spec as IFsComplexValue).ValueOA as IFsFeatStruc); - } + fs.PriorityUnion(newComplexValue.ValueOA as IFsFeatStruc); } } } @@ -3963,7 +3960,7 @@ orderby FeatureSpecKey(s) { if (fLongForm) { - tisb.AppendTsString((cv as FsClosedValue).LongNameTSS); + tisb.AppendTsString((cv as FsClosedValue)?.LongNameTSS); } else { @@ -3972,11 +3969,10 @@ orderby FeatureSpecKey(s) } else { - var complex = spec as IFsComplexValue; - if (complex != null) + if (spec is IFsComplexValue complex) { if (fLongForm) - tisb.AppendTsString((complex as FsComplexValue).LongNameTSS); + tisb.AppendTsString(((FsComplexValue)complex).LongNameTSS); else tisb.AppendTsString(complex.ShortNameTSS); } @@ -4084,7 +4080,7 @@ internal override void CopyPropertiesTo(ICmObject clone) } foreach (IFsFeatureSpecification oldSpec in FeatureSpecsOC) { - var newSpec = (oldSpec as FsFeatureSpecification).CreateNewObject(); + var newSpec = ((FsFeatureSpecification)oldSpec).CreateNewObject(); feat.FeatureSpecsOC.Add(newSpec); oldSpec.SetCloneProperties(newSpec); } @@ -4124,13 +4120,13 @@ protected override void OnBeforeObjectDeleted() m_backrefsToDelete.Clear(); foreach (ICmObject obj in ReferringObjects) { - if (obj is IFsFeatureSpecification && - (obj as IFsFeatureSpecification).FeatureRA == this) + if (obj is IFsFeatureSpecification spec && + spec.FeatureRA == this) { m_backrefsToDelete.Add(obj); } - else if (obj is IPhFeatureConstraint && - (obj as IPhFeatureConstraint).FeatureRA == this) + else if (obj is IPhFeatureConstraint con && + con.FeatureRA == this) { m_backrefsToDelete.Add(obj); } @@ -4169,16 +4165,16 @@ private void RemoveUnwantedFeatureStuff(List objectsToDeleteAlso, ICm if (obj != null && obj.IsValidObject) { bool fDelete = false; - if (obj is FsFeatStruc) + if (obj is FsFeatStruc fs) { - int cDisj = (obj as FsFeatStruc).FeatureDisjunctionsOC.Count; - int cSpec = (obj as FsFeatStruc).FeatureSpecsOC.Count; + int cDisj = fs.FeatureDisjunctionsOC.Count; + int cSpec = fs.FeatureSpecsOC.Count; if (cDisj + cSpec == 1) fDelete = true; } - else if (obj is FsFeatStrucDisj) + else if (obj is FsFeatStrucDisj fsd) { - int cContents = (obj as FsFeatStrucDisj).ContentsOC.Count; + int cContents = fsd.ContentsOC.Count; if (cContents == 1) fDelete = true; } @@ -4259,7 +4255,7 @@ public void CloneDetails(IPubHFSet copyFrom) DefaultFooterOA.InsideAlignedText = copyFrom.DefaultFooterOA.InsideAlignedText; - var owningDiv = Owner as IPubDivision; + var owningDiv = (IPubDivision)Owner; if (owningDiv.DifferentFirstHF) { // if the header and the footer were null (if they are the same as the odd page) diff --git a/src/SIL.LCModel/DomainImpl/OverridesLangProj.cs b/src/SIL.LCModel/DomainImpl/OverridesLangProj.cs index f52301a6..fbb8c45c 100644 --- a/src/SIL.LCModel/DomainImpl/OverridesLangProj.cs +++ b/src/SIL.LCModel/DomainImpl/OverridesLangProj.cs @@ -369,13 +369,14 @@ private void AddSubPartsOfSpeech(IPartOfSpeech posRoot, List rgpo /// ------------------------------------------------------------------------------------ public virtual ICmPossibility GetDefaultChartTemplate() { + ICmPossibility defaultTemplate = null; if (m_cache.LanguageProject.DiscourseDataOA == null || m_cache.LanguageProject.DiscourseDataOA.ConstChartTemplOA == null || m_cache.LanguageProject.DiscourseDataOA.ConstChartTemplOA.PossibilitiesOS.Count == 0) { - CreateDefaultTemplate(); + defaultTemplate = CreateDefaultTemplate(); } - return m_cache.LanguageProject.DiscourseDataOA.ConstChartTemplOA.PossibilitiesOS[0]; + return m_cache.LanguageProject.DiscourseDataOA?.ConstChartTemplOA?.PossibilitiesOS[0] ?? defaultTemplate; } /// @@ -464,13 +465,15 @@ internal ICmPossibility CreateColumn(ICmPossibility parent, XmlNode spec) /// ------------------------------------------------------------------------------------ public ICmPossibility GetDefaultChartMarkers() { + ICmPossibilityList defaultMarkers = null; if (m_cache.LangProject.DiscourseDataOA == null || m_cache.LangProject.DiscourseDataOA.ChartMarkersOA == null || m_cache.LangProject.DiscourseDataOA.ChartMarkersOA.PossibilitiesOS.Count == 0) { - MakeDefaultChartMarkers(); + defaultMarkers = MakeDefaultChartMarkers(); } - return m_cache.LangProject.DiscourseDataOA.ChartMarkersOA.PossibilitiesOS[0]; + return m_cache.LangProject.DiscourseDataOA?.ChartMarkersOA?.PossibilitiesOS[0] ?? + defaultMarkers!.PossibilitiesOS[0]; } /// diff --git a/src/SIL.LCModel/DomainImpl/OverridesLing_Lex.cs b/src/SIL.LCModel/DomainImpl/OverridesLing_Lex.cs index 38eb5a11..89e99c0c 100644 --- a/src/SIL.LCModel/DomainImpl/OverridesLing_Lex.cs +++ b/src/SIL.LCModel/DomainImpl/OverridesLing_Lex.cs @@ -928,7 +928,7 @@ internal IEnumerable ComplexFormRefsWithThisComponentEntry if (sequence == null) continue; if (sequence.Flid == LexEntryRefTags.kflidComponentLexemes && - (sequence.MainObject as ILexEntryRef).RefType == LexEntryRefTags.krtComplexForm) + ((ILexEntryRef)sequence.MainObject).RefType == LexEntryRefTags.krtComplexForm) { yield return sequence.MainObject as ILexEntryRef; } @@ -950,7 +950,7 @@ internal IEnumerable ComplexFormRefsWithThisPrimaryEntry if (sequence == null) continue; if (sequence.Flid == LexEntryRefTags.kflidPrimaryLexemes && - (sequence.MainObject as ILexEntryRef).RefType == LexEntryRefTags.krtComplexForm) + ((ILexEntryRef)sequence.MainObject).RefType == LexEntryRefTags.krtComplexForm) { yield return sequence.MainObject as ILexEntryRef; } @@ -969,7 +969,7 @@ internal IEnumerable ComplexFormRefsVisibleInThisEntry if (sequence == null) continue; if (sequence.Flid == LexEntryRefTags.kflidShowComplexFormsIn && - (sequence.MainObject as ILexEntryRef).RefType == LexEntryRefTags.krtComplexForm) + ((ILexEntryRef)sequence.MainObject).RefType == LexEntryRefTags.krtComplexForm) { yield return sequence.MainObject as ILexEntryRef; } @@ -1331,8 +1331,8 @@ public bool SupportsInflectionClasses() { foreach (IMoMorphSynAnalysis item in MorphoSyntaxAnalysesOC) { - if ((item is IMoInflAffMsa && (item as IMoInflAffMsa).PartOfSpeechRA != null) - || (item is IMoDerivAffMsa && (item as IMoDerivAffMsa).FromInflectionClassRA != null)) + if ((item is IMoInflAffMsa infl && infl.PartOfSpeechRA != null) + || (item is IMoDerivAffMsa deriv && deriv.FromInflectionClassRA != null)) { return true; } @@ -1411,14 +1411,14 @@ public void ReplaceMoForm(IMoForm mfOld, IMoForm mfNew) { // save the environment references, if any. IEnumerable envs = null; - if (mfOld is IMoStemAllomorph) - envs = (mfOld as IMoStemAllomorph).PhoneEnvRC.ToArray(); - else if (mfOld is IMoAffixAllomorph) - envs = (mfOld as IMoAffixAllomorph).PhoneEnvRC.ToArray(); + if (mfOld is IMoStemAllomorph stem) + envs = stem.PhoneEnvRC.ToArray(); + else if (mfOld is IMoAffixAllomorph affix) + envs = affix.PhoneEnvRC.ToArray(); IEnumerable inflClasses = null; - if (mfOld is IMoAffixForm) - inflClasses = (mfOld as IMoAffixForm).InflectionClassesRC.ToArray(); + if (mfOld is IMoAffixForm affix2) + inflClasses = affix2.InflectionClassesRC.ToArray(); // if we are converting from one affix form to another, we should save the morph type IMoMorphType oldAffMorphType = null; @@ -1454,10 +1454,10 @@ public void ReplaceMoForm(IMoForm mfOld, IMoForm mfNew) { foreach (var env in envs) { - if (mfNew is IMoStemAllomorph) - (mfNew as IMoStemAllomorph).PhoneEnvRC.Add(env); - else if (mfNew is IMoAffixAllomorph) - (mfNew as IMoAffixAllomorph).PhoneEnvRC.Add(env); + if (mfNew is IMoStemAllomorph newStem) + newStem.PhoneEnvRC.Add(env); + else if (mfNew is IMoAffixAllomorph affix3) + affix3.PhoneEnvRC.Add(env); } } @@ -1465,13 +1465,13 @@ public void ReplaceMoForm(IMoForm mfOld, IMoForm mfNew) { foreach (var inflClass in inflClasses) { - if (mfNew is IMoAffixForm) - (mfNew as IMoAffixForm).InflectionClassesRC.Add(inflClass); + if (mfNew is IMoAffixForm affixForm) + affixForm.InflectionClassesRC.Add(inflClass); } } - if (oldAffMorphType != null && mfNew is IMoAffixForm) - mfNew.MorphTypeRA = oldAffMorphType; + if (oldAffMorphType != null && mfNew is IMoAffixForm affixFormNew) + affixFormNew.MorphTypeRA = oldAffMorphType; } /// @@ -1571,14 +1571,14 @@ private IMoMorphSynAnalysis FindOrCreateMatchingAffixMsa(IMoStemMsa msa) private IMoMorphSynAnalysis FindOrCreateMatchingStemMsa(IMoMorphSynAnalysis msa) { IPartOfSpeech POS = null; - if (msa is IMoInflAffMsa) - POS = (msa as IMoInflAffMsa).PartOfSpeechRA; - else if (msa is IMoDerivAffMsa) - POS = (msa as IMoDerivAffMsa).ToPartOfSpeechRA; - else if (msa is IMoDerivStepMsa) - POS = (msa as IMoDerivStepMsa).PartOfSpeechRA; - else if (msa is IMoUnclassifiedAffixMsa) - POS = (msa as IMoUnclassifiedAffixMsa).PartOfSpeechRA; + if (msa is IMoInflAffMsa inflAffMsa) + POS = inflAffMsa.PartOfSpeechRA; + else if (msa is IMoDerivAffMsa derivAffMsa) + POS = derivAffMsa.ToPartOfSpeechRA; + else if (msa is IMoDerivStepMsa { PartOfSpeechRA: var pos }) + POS = pos; + else if (msa is IMoUnclassifiedAffixMsa unclassifiedAffMsa) + POS = unclassifiedAffMsa.PartOfSpeechRA; foreach (var msaT in MorphoSyntaxAnalysesOC) { var msaStem = msaT as IMoStemMsa; @@ -1762,7 +1762,7 @@ public void MoveSenseToCopy(ILexSense ls) public static void UpdateReferencesForSenseMove(ILexEntry leSource, ILexEntry leTarget, ILexSense ls) { var msaCorrespondence = new Dictionary(4); - (leTarget as LexEntry).ReplaceMsasForSense(ls, msaCorrespondence, leSource); + ((LexEntry)leTarget).ReplaceMsasForSense(ls, msaCorrespondence, leSource); foreach (var sense in ls.AllSenses) { foreach (var source in sense.ReferringObjects) @@ -1859,7 +1859,7 @@ private void ReplaceMsasForSense(ILexSense ls, Dictionary.CloneLcmObject(msaOld, newMsa => MorphoSyntaxAnalysesOC.Add(newMsa)); } @@ -2472,7 +2472,7 @@ public string LIFTid sLiftId = ExtractAttributeFromLiftResidue(sResidue, "id"); if (String.IsNullOrEmpty(sLiftId)) return HeadWord.Text + "_" + Guid; - int idx = sLiftId.IndexOf('_'); + int idx = sLiftId!.IndexOf('_'); if (idx >= 0) return sLiftId.Substring(0, idx) + "_" + Guid; else @@ -2614,7 +2614,7 @@ public string CitationFormSortKey(bool sortedFromEnd, int ws) if (mmt != null) { // Append 11 digit sortkey after space. sortkey = morphtype number << 10 bits - sKey = (mmt as MoForm).SortKeyMorphType(sKey); + sKey = ((MoForm)mmt).SortKeyMorphType(sKey); } return sKey; @@ -2968,7 +2968,7 @@ public void CitationFormWithAffixTypeTss(ITsIncStrBldr tsb) } // The following code for setting Ws and FontFamily are to fix LT-6238. CoreWritingSystemDefinition defVernWs = Services.WritingSystems.DefaultVernacularWritingSystem; - var entry = form.Owner as ILexEntry; + var entry = (ILexEntry)form.Owner; var hc = entry.Services.GetInstance(); if (!string.IsNullOrEmpty(prefix)) { @@ -3077,7 +3077,7 @@ internal static ILexEntryRef FindMatchingVariantEntryBackRef(IVariantComponentLe if (ler.ComponentLexemesRS.Count == 1) { // next see if we can match on the same variant lexeme form - ILexEntry variantEntry = (ler as CmObject).Owner as ILexEntry; + ILexEntry variantEntry = (ILexEntry)ler.Owner; if (variantEntry.LexemeFormOA == null || variantEntry.LexemeFormOA.Form == null) continue; int wsTargetVariant = TsStringUtils.GetWsAtOffset(targetVariantLexemeForm, 0); @@ -3422,11 +3422,10 @@ internal override void RemoveAReferenceCore(ICmObject target) /// public override void MergeObject(ICmObject objSrc, bool fLoseNoStringData) { - if (!(objSrc is ILexEntry)) + if (objSrc is not ILexEntry le) return; var homoForm = HomographFormKey; - var le = objSrc as ILexEntry; // If the lexeme forms don't match, and they both have content in the vernacular, make the other LF an allomorph. if (LexemeFormOA != null && le.LexemeFormOA != null && LexemeFormOA.Form.VernacularDefaultWritingSystem != null && le.LexemeFormOA.Form.VernacularDefaultWritingSystem != null @@ -3444,7 +3443,7 @@ public override void MergeObject(ICmObject objSrc, bool fLoseNoStringData) // merge the LexemeForm objects first, if this is possible. This is important, because otherwise the // LexemeForm objects would not get merged, and that is needed for proper handling // of references and back references. - if (LexemeFormOA != null && le.LexemeFormOA != null && LexemeFormOA.ClassID == le.LexemeFormOA.ClassID) + if (LexemeFormOA != null && le!.LexemeFormOA != null && LexemeFormOA.ClassID == le.LexemeFormOA.ClassID) { LexemeFormOA.MergeObject(le.LexemeFormOA, fLoseNoStringData); le.LexemeFormOA = null; @@ -3471,7 +3470,6 @@ public override void MergeObject(ICmObject objSrc, bool fLoseNoStringData) // base.MergeObject will call DeleteUnderlyingObject on objSrc, // which, in turn, will reset homographs for any similar entries for objSrc. - Debug.Assert(m_cache != null); // We don't allow merging items of different classes. Debug.Assert(ClassID == objSrc.ClassID); if (ClassID != objSrc.ClassID) @@ -3591,7 +3589,7 @@ public int EntryAnalysesCount { foreach (ICmObject cmo in mfo.ReferringObjects) if (cmo is IWfiMorphBundle) - count += (cmo.Owner as WfiAnalysis).OccurrencesInTexts.Count(); + count += ((WfiAnalysis)cmo.Owner).OccurrencesInTexts.Count(); } return count; } @@ -3605,10 +3603,9 @@ public IEnumerable AllStemNames get { var stemNames = new HashSet(StemNamesOC); - if (Owner.ClassID == PartOfSpeechTags.kClassId) + if (Owner is IPartOfSpeech pos) { - var owner = Owner as IPartOfSpeech; - stemNames.UnionWith(owner.AllStemNames); + stemNames.UnionWith(pos.AllStemNames); } return stemNames; } @@ -3624,10 +3621,9 @@ public IEnumerable AllInflectionClasses get { var classes = new HashSet(InflectionClassesOC); - if (Owner.ClassID == PartOfSpeechTags.kClassId) + if (Owner is IPartOfSpeech pos) { - var owner = Owner as IPartOfSpeech; - classes.UnionWith(owner.AllInflectionClasses); + classes.UnionWith(pos.AllInflectionClasses); } return classes; } @@ -3643,10 +3639,9 @@ public IEnumerable AllAffixSlots get { var slots = new HashSet(AffixSlotsOC); - if (Owner.ClassID == PartOfSpeechTags.kClassId) + if (Owner is IPartOfSpeech pos) { - var owner = Owner as IPartOfSpeech; - slots.UnionWith(owner.AllAffixSlots); + slots.UnionWith(pos.AllAffixSlots); } return slots; } @@ -3946,7 +3941,7 @@ public int NumberOfLexEntries { foreach (IMoMorphSynAnalysis msa in le.MorphoSyntaxAnalysesOC) { - if (msa is IMoStemMsa && (msa as IMoStemMsa).PartOfSpeechRA == this) + if (msa is IMoStemMsa { PartOfSpeechRA: PartOfSpeech pos } && pos == this) { ++cLex; break; @@ -4041,7 +4036,7 @@ internal IEnumerable ComplexFormRefsWithThisComponentSense if (sequence == null) continue; if (sequence.Flid == LexEntryRefTags.kflidComponentLexemes && - (sequence.MainObject as ILexEntryRef).RefType == LexEntryRefTags.krtComplexForm) + ((ILexEntryRef)sequence.MainObject).RefType == LexEntryRefTags.krtComplexForm) { yield return sequence.MainObject as ILexEntryRef; } @@ -4064,7 +4059,7 @@ internal IEnumerable ComplexFormRefsWithThisPrimarySense if (sequence == null) continue; if (sequence.Flid == LexEntryRefTags.kflidPrimaryLexemes && - (sequence.MainObject as ILexEntryRef).RefType == LexEntryRefTags.krtComplexForm) + ((ILexEntryRef)sequence.MainObject).RefType == LexEntryRefTags.krtComplexForm) { yield return sequence.MainObject as ILexEntryRef; } @@ -4084,7 +4079,7 @@ internal IEnumerable ComplexFormRefsVisibleInThisSense if (sequence == null) continue; if (sequence.Flid == LexEntryRefTags.kflidShowComplexFormsIn && - (sequence.MainObject as ILexEntryRef).RefType == LexEntryRefTags.krtComplexForm) + ((ILexEntryRef)sequence.MainObject).RefType == LexEntryRefTags.krtComplexForm) { yield return sequence.MainObject as ILexEntryRef; } @@ -4112,7 +4107,7 @@ internal IEnumerable ReferringLexReferences } /// - /// LT-18771 - Method to remove the duplicated references occurs on Undo process, + /// LT-18771 - Method to remove the duplicated references occurs on Undo process, /// the first one of duplicated item becomes invalid. So we removed here. /// private void RemoveDuplicateRefs() @@ -4408,8 +4403,8 @@ private bool FindMatchingSense(int hvoDomain, ILexEntry leCurrent) /// private void TransferExtraFieldsToSense(ILexSense sense) { - var sda = Cache.DomainDataByFlid as ISilDataAccessManaged; - var flids = (Cache.MetaDataCacheAccessor as LcmMetaDataCache).GetFields(LexSenseTags.kClassId, true, + var sda = (ISilDataAccessManaged)Cache.DomainDataByFlid; + var flids = ((LcmMetaDataCache)Cache.MetaDataCacheAccessor).GetFields(LexSenseTags.kClassId, true, (int)CellarPropertyTypeFilter.AllMulti).Except(new int[] {LexSenseTags.kflidGloss, LexSenseTags.kflidDefinition}); CopyMergeMultiStringFields(sense.Hvo, flids, Hvo, sda); foreach (var flid in ((LcmMetaDataCache)Cache.MetaDataCacheAccessor).GetFields(LexSenseTags.kClassId, true, @@ -4446,7 +4441,7 @@ private void CopyExtraFieldsToEntry(ILexEntry entry) } } var sda = Cache.DomainDataByFlid as ISilDataAccessManaged; - var flids = (Cache.MetaDataCacheAccessor as LcmMetaDataCache).GetFields(LexEntryTags.kClassId, true, + var flids = ((LcmMetaDataCache)Cache.MetaDataCacheAccessor).GetFields(LexEntryTags.kClassId, true, (int)CellarPropertyTypeFilter.AllMulti).Except(new int[] {LexEntryTags.kflidCitationForm}); CopyMergeMultiStringFields(entry.Hvo, flids, OwningEntry.Hvo, sda); } @@ -4647,7 +4642,7 @@ protected override void AddObjectSideEffectsInternal(AddObjectEventArgs e) private void SensesChangedPosition(int startIndex) { for (int i = startIndex; i < SensesOS.Count; i++) - (SensesOS[i] as LexSense).LexSenseOutlineChanged(); + ((LexSense)SensesOS[i]).LexSenseOutlineChanged(); } protected override void RemoveObjectSideEffectsInternal(RemoveObjectEventArgs e) @@ -5120,7 +5115,7 @@ public SandboxGenericMSA SandboxMSA var msaOld = MorphoSyntaxAnalysisRA; foreach (var msa in entry.MorphoSyntaxAnalysesOC) { - if ((msa as MoMorphSynAnalysis).EqualsMsa(value)) + if (((MoMorphSynAnalysis)msa).EqualsMsa(value)) { MorphoSyntaxAnalysisRA = msa; // setter handles deleting msaOld if it is no longer used. return; @@ -5209,8 +5204,8 @@ public SandboxGenericMSA SandboxMSA break; } } - MorphoSyntaxAnalysisRA = Cache.ServiceLocator.GetInstance().GetObject(msaMatch.Hvo); - if (msaOld != null && msaOld.IsValidObject && entry is LexEntry && !(entry as LexEntry).UsesMsa(msaOld)) + MorphoSyntaxAnalysisRA = Cache.ServiceLocator.GetInstance().GetObject(msaMatch!.Hvo); + if (msaOld != null && msaOld.IsValidObject && entry is LexEntry && !((LexEntry)entry).UsesMsa(msaOld)) { ReplaceReferences(msaOld, msaMatch); // ReplaceReferences may well delete this object for us. See FWR-2855. @@ -5239,7 +5234,7 @@ public string LIFTid sLiftId = LexEntry.ExtractAttributeFromLiftResidue(sResidue, "id"); if (String.IsNullOrEmpty(sLiftId)) return Guid.ToString(); - int idx = sLiftId.IndexOf('_'); + int idx = sLiftId!.IndexOf('_'); if (idx >= 0) return sLiftId.Substring(0, idx) + "_" + Guid; return Guid.ToString(); @@ -5438,10 +5433,10 @@ private void SetReversalEntriesBulkTextForWs(int ws, ITsString tssVal) if (rie.SubentriesOS.Count == 0 && Services.GetInstance().InstancesWithReversalEntry(rie).FirstOrDefault() == null) { - if (rie.Owner is ReversalIndex) - (rie.Owner as ReversalIndex).EntriesOC.Remove(rie); + if (rie.Owner is ReversalIndex index) + index.EntriesOC.Remove(rie); else - (rie.Owner as ReversalIndexEntry).SubentriesOS.Remove(rie); + ((ReversalIndexEntry)rie.Owner).SubentriesOS.Remove(rie); } } @@ -5836,15 +5831,14 @@ public string SenseNumber { string number = ""; - if (Owner is ILexEntry) + if (Owner is ILexEntry le) { - var le = Owner as ILexEntry; int idx = le.SensesOS.IndexOf(this) + 1; number = idx.ToString(); } else { - var ls = Owner as LexSense; + var ls = (LexSense)Owner; int idx = ls.SensesOS.IndexOf(this) + 1; number = ls.SenseNumber + "." + idx.ToString(); } @@ -6024,9 +6018,9 @@ public void AdjustDerivedAnalysis() var allSegs = Cache.ServiceLocator.GetInstance().AllInstances(); var wg = (from gloss in allGlosses - let bundles = (gloss.Owner as IWfiAnalysis).MorphBundlesOS.Where(bundle => bundle.SenseRA != null) + let bundles = ((IWfiAnalysis)gloss.Owner).MorphBundlesOS.Where(bundle => bundle.SenseRA != null) where bundles.Count() == 1 && bundles.First() == this && !allSegs.Any(seg => seg.AnalysesRS.Contains(gloss)) - && !(gloss.Owner as IWfiAnalysis).EvaluationsRC.Any(eval => eval.Approves && (eval.Owner as ICmAgent).Human) + && !((IWfiAnalysis)gloss.Owner).EvaluationsRC.Any(eval => eval.Approves && ((ICmAgent)eval.Owner).Human) select gloss).FirstOrDefault(); if (wg != null) @@ -6072,7 +6066,7 @@ public ILexEntryRef CreateVariantEntryAndBackRef(ILexEntryType variantType) /// the new variant entry reference public ILexEntryRef CreateVariantEntryAndBackRef(ILexEntryType variantType, ITsString tssVariantLexemeForm) { - var entry = Owner as LexEntry; + var entry = (LexEntry)Owner; return entry.CreateVariantEntryAndBackRef(this, variantType, tssVariantLexemeForm); } @@ -6211,7 +6205,7 @@ public int SenseAnalysesCount int count = 0; foreach (ICmObject cmo in ReferringObjects) if (cmo is IWfiMorphBundle) - count += (cmo.Owner as WfiAnalysis).OccurrencesInTexts.Count(); + count += ((WfiAnalysis)cmo.Owner).OccurrencesInTexts.Count(); return count; } } @@ -6724,7 +6718,7 @@ protected override void AddObjectSideEffectsInternal(AddObjectEventArgs e) switch (e.Flid) { case ReversalIndexEntryTags.kflidSenses: - var lexSense = e.ObjectAdded as LexSense; + var lexSense = (LexSense)e.ObjectAdded; if (WritingSystem != 0) // defensive, mainly for tests lexSense.ReversalEntriesBulkTextChanged(WritingSystem); ReversalEntrySensesChanged(lexSense, true); @@ -6737,7 +6731,7 @@ protected override void RemoveObjectSideEffectsInternal(RemoveObjectEventArgs e) switch (e.Flid) { case ReversalIndexEntryTags.kflidSenses: - var lexSense = e.ObjectRemoved as LexSense; + var lexSense = (LexSense)e.ObjectRemoved; if (WritingSystem != 0) // defensive, mainly for tests lexSense.ReversalEntriesBulkTextChanged(WritingSystem); ReversalEntrySensesChanged(lexSense, false); @@ -6931,7 +6925,7 @@ public void RebuildPhonRuleFeats(IEnumerable members) { foreach (var phonRuleFeat in phonRuleFeats.PossibilitiesOS) { - var prf = phonRuleFeat as IPhPhonRuleFeat; + var prf = (IPhPhonRuleFeat)phonRuleFeat; if (prf.ItemRA == null) phonRuleFeats.PossibilitiesOS.Remove(prf); else @@ -7146,10 +7140,10 @@ protected override void OnBeforeObjectDeleted() { if (obj is IPhSimpleContextNC) { - var ctx = obj as IPhSimpleContextNC; + var ctx = (IPhSimpleContextNC)obj; if (ctx.FeatureStructureRA is IPhNCFeatures) { - var feats = ctx.FeatureStructureRA as IPhNCFeatures; + var feats = (IPhNCFeatures)ctx.FeatureStructureRA; if ((feats.FeaturesOA == null) && (ctx.MinusConstrRS.Count == 1 && ctx.MinusConstrRS.Contains(this) && ctx.PlusConstrRS.Count == 0) || (ctx.PlusConstrRS.Count == 1 && ctx.PlusConstrRS.Contains(this) && ctx.MinusConstrRS.Count == 0)) @@ -7463,7 +7457,7 @@ protected override void OnBeforeObjectDeleted() { if (refObj is MoAffixAllomorph) { - var affixAllomorphReferrer = refObj as MoAffixAllomorph; + var affixAllomorphReferrer = (MoAffixAllomorph)refObj; var oldForm = affixAllomorphReferrer.Form.get_String(vernWs).Text; if (oldForm != null) { @@ -7475,7 +7469,7 @@ protected override void OnBeforeObjectDeleted() if (refObj is MoStemAllomorph) { - var stemAllomorphReferrer = refObj as MoStemAllomorph; + var stemAllomorphReferrer = (MoStemAllomorph)refObj; var oldForm = stemAllomorphReferrer.Form.get_String(vernWs).Text; if (oldForm != null) { @@ -7590,18 +7584,18 @@ void CollectVars(IPhPhonContext ctxt, List featureConstrs, switch (ctxt.ClassID) { case PhSequenceContextTags.kClassId: - var seqCtxt = ctxt as IPhSequenceContext; + var seqCtxt = (IPhSequenceContext)ctxt; foreach (var cur in seqCtxt.MembersRS) CollectVars(cur as IPhSimpleContextNC, featureConstrs, excludeCtxt); break; case PhIterationContextTags.kClassId: - var iterCtxt = ctxt as IPhIterationContext; + var iterCtxt = (IPhIterationContext)ctxt; CollectVars(iterCtxt.MemberRA, featureConstrs, excludeCtxt); break; case PhSimpleContextNCTags.kClassId: - var ncCtxt = ctxt as IPhSimpleContextNC; + var ncCtxt = (IPhSimpleContextNC)ctxt; CollectVars(ncCtxt.PlusConstrRS, featureConstrs); CollectVars(ncCtxt.MinusConstrRS, featureConstrs); break; @@ -7696,7 +7690,7 @@ public override IEnumerable ReferenceTargetCandidates(int flid) var poses = Cache.LangProject.PartsOfSpeechOA.ReallyReallyAllPossibilities; foreach (var possibility in poses) { - var pos = possibility as IPartOfSpeech; + var pos = (IPartOfSpeech)possibility; CollectInflectionClassesAndSubclasses(result, pos.AllInflectionClasses); } var prodRestricts = Cache.LangProject.MorphologicalDataOA.ProdRestrictOA.PossibilitiesOS.Cast(); @@ -7993,8 +7987,7 @@ public int MiddleIndex private int GetIndex(int index) { - bool isMiddleWithLeftSwitch; - int[] indices = GetStrucChangeIndices(out isMiddleWithLeftSwitch); + int[] indices = GetStrucChangeIndices(out _); return indices[index]; } @@ -8098,8 +8091,7 @@ public bool IsMiddleWithLeftSwitch set { - bool isMiddleWithLeftSwitch; - int[] indices = GetStrucChangeIndices(out isMiddleWithLeftSwitch); + int[] indices = GetStrucChangeIndices(out _); SetStrucChangeIndices(indices, value); } } @@ -8250,7 +8242,7 @@ public override void PreRemovalSideEffects() base.PreRemovalSideEffects(); if (Owner != null && Owner.ClassID == PhMetathesisRuleTags.kClassId) { - var rule = Owner as IPhMetathesisRule; + var rule = (IPhMetathesisRule)Owner; var ctxtToRemove = rule.UpdateStrucChange(rule.GetStrucChangeIndex(this), IndexInOwner, false); if (ctxtToRemove != null) rule.StrucDescOS.Remove(ctxtToRemove); @@ -8270,12 +8262,12 @@ protected override void AddObjectSideEffectsInternal(AddObjectEventArgs e) if (entry != null) UpdateLexEntryReferences(entry, true); UpdateMinimalLexReferences(null); - if (e.ObjectAdded is LexSense) + if (e.ObjectAdded is LexSense sense) { - List backrefs = ((LexSense)e.ObjectAdded).LexSenseReferences.Cast().ToList(); - Services.GetInstance().RegisterVirtualAsModified(e.ObjectAdded, "LexSenseReferences", + List backrefs = sense.LexSenseReferences.Cast().ToList(); + Services.GetInstance().RegisterVirtualAsModified(sense, "LexSenseReferences", backrefs); - entry = (e.ObjectAdded as LexSense).Entry; + entry = sense.Entry; } if (entry != null) entry.DateModified = DateTime.Now; @@ -8309,10 +8301,10 @@ private void UpdateMinimalLexReferences(ICmObject extraTarget) targets.Add(extraTarget); foreach (var target in targets) { - if (target is LexEntry) - uowService.RegisterVirtualAsModified(target, "MinimalLexReferences", ((LexEntry)target).MinimalLexReferences.Cast()); - else if (target is LexSense) - uowService.RegisterVirtualAsModified(target, "MinimalLexReferences", ((LexSense)target).MinimalLexReferences.Cast()); + if (target is LexEntry entry) + uowService.RegisterVirtualAsModified(entry, "MinimalLexReferences", entry.MinimalLexReferences.Cast()); + else if (target is LexSense sense) + uowService.RegisterVirtualAsModified(sense, "MinimalLexReferences", sense.MinimalLexReferences.Cast()); } } @@ -8326,13 +8318,13 @@ protected override void RemoveObjectSideEffectsInternal(RemoveObjectEventArgs e) if (entry != null) UpdateLexEntryReferences(entry, false); UpdateMinimalLexReferences(e.ObjectRemoved); - if (e.ObjectRemoved is LexSense) + if (e.ObjectRemoved is LexSense sense) { - List backrefs = ((LexSense)e.ObjectRemoved).LexSenseReferences.Cast().ToList(); + List backrefs = sense.LexSenseReferences.Cast().ToList(); // don't use this.Services, since 'this' may already have been deleted (in case Replace reduces target set to one item). - e.ObjectRemoved.Services.GetInstance().RegisterVirtualAsModified(e.ObjectRemoved, "LexSenseReferences", + e.ObjectRemoved.Services.GetInstance().RegisterVirtualAsModified(sense, "LexSenseReferences", backrefs); - entry = (e.ObjectRemoved as LexSense).Entry; + entry = sense.Entry; } if (entry != null) entry.DateModified = DateTime.Now; @@ -8412,7 +8404,7 @@ public override ITsString DeletionTextTSS { get { - var lrtOwner = Owner as ILexRefType; + var lrtOwner = (ILexRefType)Owner; var analWs = m_cache.DefaultAnalWs; var userWs = m_cache.DefaultUserWs; var tisb = TsStringUtils.MakeIncStrBldr(); @@ -8478,7 +8470,7 @@ public static List ExtractMinimalLexReferences(IEnumerable public int SequenceIndex(int hvoMember) { - var lrtOwner = Owner as ILexRefType; + var lrtOwner = (ILexRefType)Owner; switch ((MappingTypes)lrtOwner.MappingType) { case MappingTypes.kmtEntryOrSenseSequence: @@ -8504,7 +8496,7 @@ public int SequenceIndex(int hvoMember) /// The reference member which needs the abbreviation public string TypeAbbreviation(int ws, ICmObject member) { - var lrtOwner = Owner as ILexRefType; + var lrtOwner = (ILexRefType)Owner; var wsCode = SpecialWritingSystemCodes.DefaultAnalysis; if (ws < 0) { @@ -9390,7 +9382,7 @@ private void RemoveComponentFromVisibilityLists(ICmObject objRemoved) // Not, however, if it is still in ComponentLexemes, as may for example happen when they are being re-ordered. if (ComponentLexemesRS.Contains(objRemoved)) return; - PrimaryLexemesRS.Remove(objRemoved); + PrimaryLexemesRS.Remove(objRemoved); ShowComplexFormsInRS.Remove(objRemoved); } @@ -9730,12 +9722,12 @@ public void ConvertLexEntryType(ILexEntryType lexEntryType) { if (obj.ClassID == WfiMorphBundleTags.kClassId) { - var wfiMB = obj as IWfiMorphBundle; + var wfiMB = (IWfiMorphBundle)obj; wfiMB.InflTypeRA = null; } else { - var lexEntryRef = obj as ILexEntryRef; + var lexEntryRef = (ILexEntryRef)obj; int i = lexEntryRef.VariantEntryTypesRS.IndexOf(lexEntryType); lexEntryRef.VariantEntryTypesRS.RemoveAt(i); lexEntryRef.VariantEntryTypesRS.Insert(i, this); diff --git a/src/SIL.LCModel/DomainImpl/OverridesLing_MoClasses.cs b/src/SIL.LCModel/DomainImpl/OverridesLing_MoClasses.cs index ded20631..e61b82a8 100644 --- a/src/SIL.LCModel/DomainImpl/OverridesLing_MoClasses.cs +++ b/src/SIL.LCModel/DomainImpl/OverridesLing_MoClasses.cs @@ -191,9 +191,9 @@ public bool CanDeleteIfSenseDeleted(ILexSense senseToDelete) return false; } var allMoMorphAdhocProhib = servLoc.GetInstance().AllInstances(); - var mapCount = (allMoMorphAdhocProhib.Where(map => map.FirstMorphemeRA == this + var mapCount = allMoMorphAdhocProhib.Where(map => map.FirstMorphemeRA == this || map.MorphemesRS.Contains(this) - || map.RestOfMorphsRS.Contains(this))).Count(); + || map.RestOfMorphsRS.Contains(this)).Count(); if (mapCount > 0) return false; int msaCount = servLoc.GetInstance().AllInstances().Count(msa => msa.ComponentsRS.Contains(this)); @@ -405,7 +405,7 @@ public virtual IEnumerable MorphTypes /// public virtual IMoMorphSynAnalysis UpdateOrReplace(SandboxGenericMSA sandboxMsa) { - ILexEntry le = Owner as ILexEntry; + ILexEntry le = (ILexEntry)Owner; foreach (MoMorphSynAnalysis msa in le.MorphoSyntaxAnalysesOC) { // Check other extant MSAs to see if they match the updated one. @@ -502,16 +502,12 @@ public void SwitchReferences(IMoMorphSynAnalysis sourceMsa) { foreach (var obj in sourceMsa.ReferringObjects) { - if (obj is IWfiMorphBundle) + if (obj is IWfiMorphBundle wmb) { - IWfiMorphBundle wmb = obj as IWfiMorphBundle; - Debug.Assert(wmb.MsaRA == sourceMsa); wmb.MsaRA = this; } - else if (obj is ILexSense) + else if (obj is ILexSense sense) { - ILexSense sense = obj as ILexSense; - Debug.Assert(sense.MorphoSyntaxAnalysisRA == sourceMsa); sense.MorphoSyntaxAnalysisRA = this; } else @@ -739,7 +735,7 @@ public override bool EqualsMsa(IMoMorphSynAnalysis msa) var derivMsa = (IMoDerivAffMsa)msa; - return (DomainObjectServices.AreEquivalent(FromMsFeaturesOA, derivMsa.FromMsFeaturesOA) + return DomainObjectServices.AreEquivalent(FromMsFeaturesOA, derivMsa.FromMsFeaturesOA) && DomainObjectServices.AreEquivalent(ToMsFeaturesOA, derivMsa.ToMsFeaturesOA) && FromPartOfSpeechRA == derivMsa.FromPartOfSpeechRA && ToPartOfSpeechRA == derivMsa.ToPartOfSpeechRA @@ -747,7 +743,7 @@ public override bool EqualsMsa(IMoMorphSynAnalysis msa) && FromStemNameRA == derivMsa.FromStemNameRA && ToInflectionClassRA == derivMsa.ToInflectionClassRA && FromProdRestrictRC.IsEquivalent(derivMsa.FromProdRestrictRC) - && ToProdRestrictRC.IsEquivalent(derivMsa.ToProdRestrictRC)); + && ToProdRestrictRC.IsEquivalent(derivMsa.ToProdRestrictRC); } /// @@ -1190,7 +1186,7 @@ public override string InterlinearName /// true, if the field is required. public override bool IsFieldRequired(int flid) { - return (flid == MoStemMsaTags.kflidPartOfSpeech); + return flid == MoStemMsaTags.kflidPartOfSpeech; } /// @@ -1309,7 +1305,7 @@ public override ITsString LongNameTs return CmPossibility.BestAnalysisOrVernName(m_cache, PartOfSpeechRA); var userWs = m_cache.DefaultUserWs; - var entry = Owner as ILexEntry; + var entry = (ILexEntry)Owner; foreach (var form in entry.AllAllomorphs) { // LT-7075 was crashing when it was null, @@ -1548,7 +1544,7 @@ private bool OwningLexEntryHasProCliticOrEnclitic(HashSet> props try { - ILexEntry entry = Owner as ILexEntry; + var entry = (ILexEntry)Owner; propsToMonitor.Add(new Tuple(entry.Hvo, LexEntryTags.kflidLexemeForm)); propsToMonitor.Add(new Tuple(entry.Hvo, LexEntryTags.kflidAlternateForms)); @@ -1618,7 +1614,7 @@ protected override void AddObjectSideEffectsInternal(AddObjectEventArgs e) switch (e.Flid) { case MoInflAffMsaTags.kflidSlots: - var target = ((IMoInflAffixSlot) e.ObjectAdded); + var target = (IMoInflAffixSlot) e.ObjectAdded; var flid = m_cache.MetaDataCache.GetFieldId2(MoInflAffixSlotTags.kClassId, "Affixes", false); var newGuids = (from msa in target.Affixes select msa.Guid).ToArray(); @@ -1637,7 +1633,7 @@ protected override void RemoveObjectSideEffectsInternal(RemoveObjectEventArgs e) switch (e.Flid) { case MoInflAffMsaTags.kflidSlots: - var target = ((IMoInflAffixSlot)e.ObjectRemoved); + var target = (IMoInflAffixSlot)e.ObjectRemoved; var flid = m_cache.MetaDataCache.GetFieldId2(MoInflAffixSlotTags.kClassId, "Affixes", false); var newGuids = (from msa in target.Affixes select msa.Guid).ToArray(); @@ -1785,7 +1781,7 @@ public override bool EqualsMsa(SandboxGenericMSA msa) // TODO: Add checks for other properties, when we support using them. if (msa.Slot == null) - return (SlotsRC.Count == 0); + return SlotsRC.Count == 0; else return SlotsRC.Count == 1 && SlotsRC.Contains(msa.Slot); } @@ -1805,7 +1801,7 @@ public override string ShortName { get { - var entry = Owner as ILexEntry; + var entry = (ILexEntry)Owner; var sb = new StringBuilder(); sb.Append(entry.CitationFormWithAffixType); sb.Append(" "); @@ -1885,9 +1881,9 @@ public override ITsString ShortNameTSS { get { - var entry = Owner as ILexEntry; + var entry = (LexEntry)Owner; var tisb = TsStringUtils.MakeIncStrBldr(); - (entry as LexEntry).CitationFormWithAffixTypeTss(tisb); + entry.CitationFormWithAffixTypeTss(tisb); tisb.Append(" "); var tssGloss = GetFirstGlossOfMSAThatMatchesTss(entry.SensesOS); if (tssGloss == null || tssGloss.Length == 0) @@ -2639,12 +2635,12 @@ protected override void SetDefaultValuesAfterInit() /// private IEnumerable GetAllSlots() { - var pos = ((IPartOfSpeech) OwnerOfClass(PartOfSpeechTags.kClassId)); + var pos = (IPartOfSpeech) OwnerOfClass(PartOfSpeechTags.kClassId); while (pos != null) { foreach (var slot in pos.AffixSlotsOC) yield return slot; - pos = ((IPartOfSpeech) pos.OwnerOfClass(PartOfSpeechTags.kClassId)); + pos = (IPartOfSpeech) pos.OwnerOfClass(PartOfSpeechTags.kClassId); } } private IEnumerable GetPrefixSlots() @@ -2676,7 +2672,7 @@ public static IEnumerable GetSomeSlots(LcmCache cache, IEnumerable Affixes get { ((ICmObjectRepositoryInternal)Services.ObjectRepository).EnsureCompleteIncomingRefsFrom(MoInflAffMsaTags.kflidSlots); - return (from msa in m_incomingRefs + return from msa in m_incomingRefs where msa.Source is IMoInflAffMsa && ((IMoInflAffMsa) msa.Source).SlotsRC.Contains(this) - select (IMoInflAffMsa) msa.Source); + select (IMoInflAffMsa) msa.Source; } } @@ -2766,11 +2762,11 @@ public IEnumerable OtherInflectionalAffixLexEntries { get { - return (from le in Services.GetInstance().AllInstances() + return from le in Services.GetInstance().AllInstances() where le.MorphoSyntaxAnalysesOC.Any(msa => msa is IMoInflAffMsa) && !le.MorphoSyntaxAnalysesOC.Any( msa => msa is IMoInflAffMsa && ((IMoInflAffMsa) msa).SlotsRC.Contains(this)) - select le); + select le; } } @@ -2982,7 +2978,7 @@ partial void MorphTypeRASideEffects(IMoMorphType oldObjValue, IMoMorphType newOb ClearMonomorphemicMorphData(); if (Owner is LexEntry && Owner.IsValidObject) { - var entry = ((LexEntry) Owner); + var entry = (LexEntry) Owner; // Now we have to figure out the old PrimaryMorphType of the entry. // It is determined by the first item in this list which HAD a morph type (if any) var morphs = entry.AlternateFormsOS.Reverse().ToList(); @@ -2993,7 +2989,7 @@ partial void MorphTypeRASideEffects(IMoMorphType oldObjValue, IMoMorphType newOb { // If the morpheme is this, the one that is changing, then we consider // the old value that this is changing from, in determining the old PMT. - var mt = (morph == this ? oldObjValue : morph.MorphTypeRA); + var mt = morph == this ? oldObjValue : morph.MorphTypeRA; if (mt != null) { oldPrimaryType = mt; @@ -3023,7 +3019,7 @@ protected override void SetDefaultValuesAfterInit() return; // this IS the lexeme form, we can't usefully copy anything from it. //When adding an allomorph we want the morphtype to match that of the LexemeForm for the LexEntry - m_MorphTypeRA = (Owner as LexEntry).LexemeFormOA.MorphTypeRA; + m_MorphTypeRA = ((LexEntry)Owner).LexemeFormOA.MorphTypeRA; } /// @@ -3384,10 +3380,8 @@ public ITsString LongNameTSS m_cache.DefaultAnalWs); tisb.Append(post); } - if (Owner is ILexEntry) + if (Owner is ILexEntry le) { - var le = Owner as ILexEntry; - tisb.Append(" ("); if (le.SensesOS.Count > 0) { @@ -3434,7 +3428,7 @@ public override ITsString ShortNameTSS get { var tss = Form.VernacularDefaultWritingSystem; - if (tss != null || tss.Length > 0) + if (tss?.Length > 0) return tss; return TsStringUtils.MakeString( @@ -3596,12 +3590,12 @@ where morphType.IsStemType var stemNames = new HashSet(); if (Owner.ClassID == LexEntryTags.kClassId) { - ILexEntry entry = Owner as ILexEntry; + var entry = (ILexEntry)Owner; foreach (IMoMorphSynAnalysis msa in entry.MorphoSyntaxAnalysesOC) { if (msa.ClassID == MoStemMsaTags.kClassId) { - IMoStemMsa infstemmsa = msa as IMoStemMsa; + var infstemmsa = (IMoStemMsa)msa; IPartOfSpeech pos = infstemmsa.PartOfSpeechRA; if (pos != null) stemNames.UnionWith(pos.AllStemNames.Cast()); @@ -3727,7 +3721,7 @@ where morphType.IsAffixType { if (msa is IMoInflAffMsa) { - var infafxmsa = msa as IMoInflAffMsa; + var infafxmsa = (IMoInflAffMsa)msa; var pos = infafxmsa.PartOfSpeechRA; if (pos != null) classes.UnionWith(pos.AllInflectionClasses.Cast()); @@ -3739,7 +3733,7 @@ where morphType.IsAffixType // may have the inflection classes, one or more of which this allomorph may go with. else if (msa is IMoDerivAffMsa) { - var drvafxmsa = msa as IMoDerivAffMsa; + var drvafxmsa = (IMoDerivAffMsa)msa; var pos = drvafxmsa.FromPartOfSpeechRA; if (pos != null) classes.UnionWith(pos.AllInflectionClasses.Cast()); @@ -3768,7 +3762,7 @@ public override bool IsFieldRelevant(int flid, HashSet> propsToM // entry include an inflectional affix MSA. // Todo JohnT: SupportsInflectionClasses should possibly return propsToMonitor info. - ILexEntry entry = Owner as ILexEntry; + var entry = (ILexEntry)Owner; return entry.SupportsInflectionClasses() && base.IsFieldRelevant(flid, propsToMonitor); } } @@ -3868,13 +3862,13 @@ protected override void RemoveObjectSideEffectsInternal(RemoveObjectEventArgs e) switch (mapping.ClassID) { case MoCopyFromInputTags.kClassId: - var copy = mapping as IMoCopyFromInput; + var copy = (IMoCopyFromInput)mapping; if (copy.ContentRA == ctxtOrVar) OutputOS.Remove(copy); break; case MoModifyFromInputTags.kClassId: - var modify = mapping as IMoModifyFromInput; + var modify = (IMoModifyFromInput)mapping; if (modify.ContentRA == ctxtOrVar) OutputOS.Remove(modify); break; @@ -4030,9 +4024,9 @@ public override bool CheckConstraints(int flidToCheck, bool createAnnotation, ou /// true, if the field is required. public override bool IsFieldRequired(int flid) { - return ((flid == MoMorphAdhocProhibTags.kflidFirstMorpheme) + return (flid == MoMorphAdhocProhibTags.kflidFirstMorpheme) || (flid == MoMorphAdhocProhibTags.kflidRestOfMorphs) - ); + ; } /// @@ -4058,7 +4052,7 @@ public override string ShortName partial void FirstMorphemeRASideEffects(IMoMorphSynAnalysis oldObjValue, IMoMorphSynAnalysis newObjValue) { - if (oldObjValue == newObjValue || (oldObjValue == null || !oldObjValue.CanDelete)) + if (oldObjValue == newObjValue || oldObjValue == null || !oldObjValue.CanDelete) return; // Nothing to do. // Wipe out the old MSA. @@ -4194,9 +4188,9 @@ public override bool CheckConstraints(int flidToCheck, bool createAnnotation, ou /// true, if the field is required. public override bool IsFieldRequired(int flid) { - return ((flid == (int)MoAlloAdhocProhibTags.kflidFirstAllomorph) + return (flid == (int)MoAlloAdhocProhibTags.kflidFirstAllomorph) || (flid == (int)MoAlloAdhocProhibTags.kflidRestOfAllos) - ); + ; } /// @@ -4416,7 +4410,6 @@ public bool IsSuffixishType /// True, if the two morph types are ambiguous, otherwise false. public bool IsAmbiguousWith(IMoMorphType other) { - Debug.Assert(other != null); var areAmbiguous = false; switch (Guid.ToString()) @@ -4436,34 +4429,34 @@ public bool IsAmbiguousWith(IMoMorphType other) } break; case MoMorphTypeTags.kMorphPhrase: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphDiscontiguousPhrase); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphDiscontiguousPhrase; break; case MoMorphTypeTags.kMorphDiscontiguousPhrase: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphPhrase); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphPhrase; break; case MoMorphTypeTags.kMorphBoundStem: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphBoundRoot); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphBoundRoot; break; case MoMorphTypeTags.kMorphBoundRoot: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphBoundStem); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphBoundStem; break; case MoMorphTypeTags.kMorphInfix: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphInfixingInterfix); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphInfixingInterfix; break; case MoMorphTypeTags.kMorphInfixingInterfix: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphInfix); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphInfix; break; case MoMorphTypeTags.kMorphPrefix: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphPrefixingInterfix); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphPrefixingInterfix; break; case MoMorphTypeTags.kMorphPrefixingInterfix: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphPrefix); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphPrefix; break; case MoMorphTypeTags.kMorphSuffix: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphSuffixingInterfix); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphSuffixingInterfix; break; case MoMorphTypeTags.kMorphSuffixingInterfix: - areAmbiguous = (other.Guid == MoMorphTypeTags.kguidMorphSuffix); + areAmbiguous = other.Guid == MoMorphTypeTags.kguidMorphSuffix; break; default: break; diff --git a/src/SIL.LCModel/DomainImpl/OverridesLing_Wfi.cs b/src/SIL.LCModel/DomainImpl/OverridesLing_Wfi.cs index a29b65cf..53ed6045 100644 --- a/src/SIL.LCModel/DomainImpl/OverridesLing_Wfi.cs +++ b/src/SIL.LCModel/DomainImpl/OverridesLing_Wfi.cs @@ -296,13 +296,13 @@ public IWfiAnalysis Analysis partial void FormSideEffects(ITsString originalValue, ITsString newValue) { - var repo = Services.GetInstance() as IPunctuationFormRepositoryInternal; + var repo = (IPunctuationFormRepositoryInternal)Services.GetInstance(); repo.UpdateForm(originalValue, this); } protected override void OnBeforeObjectDeleted() { - var repo = Services.GetInstance() as IPunctuationFormRepositoryInternal; + var repo = (IPunctuationFormRepositoryInternal)Services.GetInstance(); repo.RemoveForm(Form); base.OnBeforeObjectDeleted(); @@ -602,7 +602,7 @@ protected override void ITsStringAltChangedSideEffectsInternal(int multiAltFlid, { if (multiAltFlid == WfiWordformTags.kflidForm) { - var repo = Services.GetInstance() as IWfiWordformRepositoryInternal; + var repo = (IWfiWordformRepositoryInternal)Services.GetInstance(); repo.UpdateForm(originalValue, this, alternativeWs.Handle); } base.ITsStringAltChangedSideEffectsInternal(multiAltFlid, alternativeWs, originalValue, newValue); @@ -610,7 +610,7 @@ protected override void ITsStringAltChangedSideEffectsInternal(int multiAltFlid, protected override void OnBeforeObjectDeleted() { - var repo = Services.GetInstance() as IWfiWordformRepositoryInternal; + var repo = (IWfiWordformRepositoryInternal)Services.GetInstance(); foreach (int ws in Form.AvailableWritingSystemIds) repo.RemoveForm(Form.get_String(ws), ws); RegisterVirtualsModifiedForObjectDeletion(((IServiceLocatorInternal)m_cache.ServiceLocator).UnitOfWorkService); @@ -958,9 +958,9 @@ public override ITsString DeletionTextTSS int annotationCount = 0; foreach (ICmObject cmo in ReferringObjects) { - if (cmo is ISegment) + if (cmo is ISegment segment) { - foreach (var x in (cmo as ISegment).AnalysesRS) + foreach (var x in segment.AnalysesRS) { if (x == this) ++annotationCount; @@ -1245,7 +1245,7 @@ public override ITsString DeletionTextTSS bool isParserApproved = false; foreach (var eval in m_EvaluationsRC) { - ICmAgent agent = eval.Owner as ICmAgent; + ICmAgent agent = (ICmAgent)eval.Owner; if (!agent.Human && eval.Approves && !isParserApproved) isParserApproved = true; } @@ -1253,9 +1253,9 @@ public override ITsString DeletionTextTSS // Note that this analysis may occur more than once in a single segment. foreach (ICmObject cmo in ReferringObjects) { - if (cmo is ISegment) + if (cmo is ISegment segment) { - foreach (var x in (cmo as ISegment).AnalysesRS) + foreach (var x in segment.AnalysesRS) { if (x == this) ++annotationCount; @@ -1270,9 +1270,9 @@ public override ITsString DeletionTextTSS { foreach (ICmObject cmo in gloss.ReferringObjects) { - if (cmo is ISegment) + if (cmo is ISegment segment) { - foreach (var x in (cmo as ISegment).AnalysesRS) + foreach (var x in segment.AnalysesRS) { if (x == gloss) ++annotationCount; diff --git a/src/SIL.LCModel/DomainImpl/OverridesNotebk.cs b/src/SIL.LCModel/DomainImpl/OverridesNotebk.cs index 76aede49..4e7e16c6 100644 --- a/src/SIL.LCModel/DomainImpl/OverridesNotebk.cs +++ b/src/SIL.LCModel/DomainImpl/OverridesNotebk.cs @@ -323,7 +323,7 @@ private ITsString SubrecordIndexTSS(ITsStrBldr bldr) return bldr.GetString(); int idx = this.IndexInOwner + 1; bldr.Replace(0, 0, String.Format("{0}.", idx.ToString()), null); - return (Owner as RnGenericRec).SubrecordIndexTSS(bldr); + return ((RnGenericRec)Owner).SubrecordIndexTSS(bldr); } partial void ValidateFurtherQuestionsOA(ref IStText newObjValue) { CheckNotNull(newObjValue);} diff --git a/src/SIL.LCModel/DomainImpl/ScrBook.cs b/src/SIL.LCModel/DomainImpl/ScrBook.cs index baeac531..bd53c54f 100644 --- a/src/SIL.LCModel/DomainImpl/ScrBook.cs +++ b/src/SIL.LCModel/DomainImpl/ScrBook.cs @@ -422,13 +422,10 @@ public FootnoteLocationInfo FindNextFootnote(int iSection, int iParagraph, int i } ILcmOwningSequence sections = SectionsOS; - IScrSection section = null; - if (footnote == null) - section = sections[iSection]; if (tag == ScrSectionTags.kflidHeading) { - footnote = section.HeadingOA.FindNextFootnote(ref iParagraph, ref ich, + footnote = sections[iSection].HeadingOA.FindNextFootnote(ref iParagraph, ref ich, fSkipCurrentPos); if (footnote == null) { @@ -441,15 +438,14 @@ public FootnoteLocationInfo FindNextFootnote(int iSection, int iParagraph, int i if (tag == ScrSectionTags.kflidContent) { - footnote = section.ContentOA.FindNextFootnote(ref iParagraph, ref ich, + footnote = sections[iSection].ContentOA.FindNextFootnote(ref iParagraph, ref ich, fSkipCurrentPos); } while (footnote == null && iSection < sections.Count - 1) { iSection++; - section = sections[iSection]; - footnote = section.FindFirstFootnote(out iParagraph, out ich, out tag); + footnote = sections[iSection].FindFirstFootnote(out iParagraph, out ich, out tag); } if (footnote != null) @@ -520,7 +516,7 @@ public IScrFootnote FindPrevFootnote(ref int iSection, ref int iParagraph, ref i if (tagTmp == ScrSectionTags.kflidContent) { - footnote = section.ContentOA.FindPreviousFootnote(ref iParagraphTmp, + footnote = section!.ContentOA.FindPreviousFootnote(ref iParagraphTmp, ref ichTmp, fSkipFirstRun); if (footnote == null) { @@ -533,7 +529,7 @@ public IScrFootnote FindPrevFootnote(ref int iSection, ref int iParagraph, ref i if (tagTmp == ScrSectionTags.kflidHeading) { - footnote = section.HeadingOA.FindPreviousFootnote(ref iParagraphTmp, + footnote = section!.HeadingOA.FindPreviousFootnote(ref iParagraphTmp, ref ichTmp, fSkipFirstRun); while (footnote == null && iSectionTmp > 0) { @@ -841,7 +837,6 @@ private void AddFootnoteRefsInText(IStText text, ref BCVRef footnoteRef) public void InitTitlePara() { IStText titleText = TitleOA; - Debug.Assert(titleText != null && titleText.ParagraphsOS.Count == 0); IStTxtPara para = titleText.AddNewTextPara(ScrStyleNames.MainBookTitle); // set the title text to the vernacular writing system. @@ -1289,7 +1284,7 @@ public OverwriteType DetermineOverwritability(IScrBook savedVersion, out string { // All revision sections are new to the current. So everything is fine. } - else if (firstScrSec == null && firstRevScrSec == null) + else if (firstScrSec == null || firstRevScrSec == null) { // There are no scripture sections in either the current or the revision, so // lets just give up! diff --git a/src/SIL.LCModel/DomainImpl/ScrBookRef.cs b/src/SIL.LCModel/DomainImpl/ScrBookRef.cs index 9771b9f1..ba6cadd8 100644 --- a/src/SIL.LCModel/DomainImpl/ScrBookRef.cs +++ b/src/SIL.LCModel/DomainImpl/ScrBookRef.cs @@ -53,7 +53,6 @@ public string UIBookAbbrev // UBS book code if (string.IsNullOrEmpty(sBookAbbrev) || sBookAbbrev == BookAbbrev.NotFoundTss.Text) sBookAbbrev = ScrReference.NumberToBookCode(IndexInOwner + 1); - System.Diagnostics.Debug.Assert(sBookAbbrev != null && sBookAbbrev != String.Empty); return sBookAbbrev.Trim(); } @@ -80,7 +79,6 @@ public string UIBookName // UBS code, if all else fails. if (string.IsNullOrEmpty(sBookName) || sBookName == BookName.NotFoundTss.Text) sBookName = ScrReference.NumberToBookCode(IndexInOwner + 1); - System.Diagnostics.Debug.Assert(sBookName != null && sBookName != String.Empty); return sBookName.Trim(); } diff --git a/src/SIL.LCModel/DomainImpl/ScrTxtPara.cs b/src/SIL.LCModel/DomainImpl/ScrTxtPara.cs index ac109252..d8a6433c 100644 --- a/src/SIL.LCModel/DomainImpl/ScrTxtPara.cs +++ b/src/SIL.LCModel/DomainImpl/ScrTxtPara.cs @@ -1943,9 +1943,7 @@ protected override void OnContentsChanged(ITsString originalValue, ITsString new if (OwningSection != null) ((ScrSection)OwningSection).AdjustReferences(); - if ((originalValue == null && newValue != null) || - (originalValue != null && newValue == null) || - (originalValue != null && originalValue.Text != newValue.Text)) + if (!(originalValue == null && newValue == null) && originalValue?.Text != newValue?.Text) { MarkBackTranslationsAsUnfinished(); } diff --git a/src/SIL.LCModel/DomainImpl/Scripture.cs b/src/SIL.LCModel/DomainImpl/Scripture.cs index b86e995c..e9bb6475 100644 --- a/src/SIL.LCModel/DomainImpl/Scripture.cs +++ b/src/SIL.LCModel/DomainImpl/Scripture.cs @@ -1042,7 +1042,7 @@ public ITsString BookChapterVerseBridgeAsTss(IStText stText, int ws) { IScrFootnote footnote = Services.GetInstance().GetObject(stText.Hvo); string footnoteRefStr = ContainingRefAsString(footnote); - ScrBook book = footnote.Owner as ScrBook; + ScrBook book = (ScrBook)footnote.Owner; ITsString tssBook = book.Name.get_String(ws); if (tssBook.Length > 0) { diff --git a/src/SIL.LCModel/DomainImpl/StText.cs b/src/SIL.LCModel/DomainImpl/StText.cs index c84a41cc..7ca0d6ca 100644 --- a/src/SIL.LCModel/DomainImpl/StText.cs +++ b/src/SIL.LCModel/DomainImpl/StText.cs @@ -224,9 +224,8 @@ private ITsString TitleForWs(int ws) } } } - else if (Owner is IText) + else if (Owner is IText text) { - IText text = Owner as IText; tssTitle = text.Name.get_String(ws); } return tssTitle ?? TsStringUtils.EmptyString(Cache.DefaultAnalWs); diff --git a/src/SIL.LCModel/DomainImpl/StTxtPara.cs b/src/SIL.LCModel/DomainImpl/StTxtPara.cs index 63e944ea..d9ad9e38 100644 --- a/src/SIL.LCModel/DomainImpl/StTxtPara.cs +++ b/src/SIL.LCModel/DomainImpl/StTxtPara.cs @@ -81,7 +81,7 @@ public virtual ITsString Reference(ISegment seg, int ich) if (!fUsingAbbreviation) tssName = stText.Title.BestVernacularAnalysisAlternative; - ITsStrBldr bldr = tssName.GetBldr(); + ITsStrBldr bldr = tssName!.GetBldr(); // If we didn't find a "best", reset to an empty string. if (bldr.Length > 0 && bldr.Text == stText.Title.NotFoundTss.Text) bldr.ReplaceTsString(0, bldr.Length, null); diff --git a/src/SIL.LCModel/DomainImpl/Vectors.cs b/src/SIL.LCModel/DomainImpl/Vectors.cs index 061a0cd5..06b72a36 100644 --- a/src/SIL.LCModel/DomainImpl/Vectors.cs +++ b/src/SIL.LCModel/DomainImpl/Vectors.cs @@ -1991,7 +1991,7 @@ public override void Insert(int index, T obj) Insert(eventArgs); // Owning Insert may have Removed from a previous owner if (removeEventArgs != null && removeEventArgs.DelaySideEffects) - ((ICmObjectInternal) oldOwner).RemoveObjectSideEffects(removeEventArgs); + ((ICmObjectInternal) oldOwner)!.RemoveObjectSideEffects(removeEventArgs); } /// ------------------------------------------------------------------------------------ diff --git a/src/SIL.LCModel/DomainServices/AnalysisGuessServices.cs b/src/SIL.LCModel/DomainServices/AnalysisGuessServices.cs index b1e2b995..739258f6 100644 --- a/src/SIL.LCModel/DomainServices/AnalysisGuessServices.cs +++ b/src/SIL.LCModel/DomainServices/AnalysisGuessServices.cs @@ -1020,9 +1020,9 @@ private void GetMainEntryAndSense(ILexEntry entryOrVariant, out ILexEntry mainEn { // get the main entry or sense. var component = entryRef.ComponentLexemesRS[0] as IVariantComponentLexeme; - if (component is ILexSense) + if (component is ILexSense sense1) { - sense = component as ILexSense; + sense = sense1; mainEntry = sense.Entry; } else diff --git a/src/SIL.LCModel/DomainServices/AnalysisOccurrence.cs b/src/SIL.LCModel/DomainServices/AnalysisOccurrence.cs index cd6b6a31..64b2a8a3 100644 --- a/src/SIL.LCModel/DomainServices/AnalysisOccurrence.cs +++ b/src/SIL.LCModel/DomainServices/AnalysisOccurrence.cs @@ -225,9 +225,9 @@ public IEnumerable GetAdvancingOccurrencesInclusiveOf(AnalysisOccurre // Need to copy out end of first segment, any segments in between and beginning of second segment return CopyOutAnalysesFromMultipleSegments(point2); } - var para1 = Segment.Owner as IStTxtPara; + var para1 = (IStTxtPara)Segment.Owner; var para2 = point2.Segment.Owner as IStTxtPara; - if (!(para1.Owner as IStText).ParagraphsOS.Contains(para2)) + if (!((IStText)para1.Owner).ParagraphsOS.Contains(para2)) { throw new ArgumentOutOfRangeException("point2", "AnalysisOccurrences are not within the same Text!"); } @@ -348,7 +348,7 @@ private IEnumerable CopyOutAnalysesFromMultipleSegments(AnalysisOccur { // Need to copy out end of first segment, any segments in between and beginning of second segment var result = new List(); - var paraSegs = (Segment.Owner as IStTxtPara).SegmentsOS; + var paraSegs = ((IStTxtPara)Segment.Owner).SegmentsOS; if (paraSegs == null) throw new NullReferenceException("Unexpected error!"); for (var i = Segment.IndexInOwner; i <= point2.Segment.IndexInOwner; i++) diff --git a/src/SIL.LCModel/DomainServices/BaseStyleInfo.cs b/src/SIL.LCModel/DomainServices/BaseStyleInfo.cs index 3379b9bb..8bb24098 100644 --- a/src/SIL.LCModel/DomainServices/BaseStyleInfo.cs +++ b/src/SIL.LCModel/DomainServices/BaseStyleInfo.cs @@ -764,7 +764,9 @@ public BaseStyleInfo(BaseStyleInfo copyFrom, string newName) public BaseStyleInfo(IStStyle style, CoreWritingSystemDefinition forceStyleInfo) : this() { - Debug.Assert(style != null); + if (style == null) + throw new ArgumentNullException("style"); + SetPropertiesBasedOnStyle(style, forceStyleInfo); m_cache = style.Cache; diff --git a/src/SIL.LCModel/DomainServices/BootstrapNewLanguageProject.cs b/src/SIL.LCModel/DomainServices/BootstrapNewLanguageProject.cs index 1e29353c..6cfdfedd 100644 --- a/src/SIL.LCModel/DomainServices/BootstrapNewLanguageProject.cs +++ b/src/SIL.LCModel/DomainServices/BootstrapNewLanguageProject.cs @@ -93,8 +93,7 @@ private static void SetupTranslationTypesAndKeyTermsList(ILangProject lp) { var servLoc = lp.Cache.ServiceLocator; var dataReader = (IDataReader)servLoc.GetInstance(); - var listFactory = servLoc.GetInstance() as ICmPossibilityListFactoryInternal; - Debug.Assert(listFactory != null, "ServiceLocator has no instance of ICmPossibilityListFactory."); + var listFactory = (ICmPossibilityListFactoryInternal)servLoc.GetInstance(); var list = listFactory.Create( CmPossibilityListTags.kguidTranslationTypes, @@ -102,8 +101,7 @@ private static void SetupTranslationTypesAndKeyTermsList(ILangProject lp) lp.TranslationTagsOA = list; lp.TranslationTagsOA.ItemClsid = CmPossibilityTags.kClassId; - var possFactory = servLoc.GetInstance() as ICmPossibilityFactoryInternal; - Debug.Assert(possFactory != null, "ServiceLocator has no instance of ICmPossibilityFactory."); + var possFactory = (ICmPossibilityFactoryInternal)servLoc.GetInstance(); // Back trans item. possFactory.Create( @@ -142,8 +140,7 @@ private static void SetupAgents(ILangProject lp) { var servLoc = lp.Cache.ServiceLocator; var dataReader = (IDataReader)servLoc.GetInstance(); - var agentFactory = servLoc.GetInstance() as ICmAgentFactoryInternal; - Debug.Assert(agentFactory != null, "ServiceLocator has no instance of ICmAgentFactory."); + var agentFactory = (ICmAgentFactoryInternal)servLoc.GetInstance(); var agent = agentFactory.Create( CmAgentTags.kguidAgentDefUser, dataReader.GetNextRealHvo(), @@ -198,7 +195,7 @@ private static ICmAnnotationDefn AddAnnotationDefn(ICmPossibilityList posList, G var cache = posList.Cache; var servLoc = cache.ServiceLocator; var dataReader = (IDataReader)servLoc.GetInstance(); - var posFactory = servLoc.GetInstance() as ICmAnnotationDefnFactoryInternal; + var posFactory = (ICmAnnotationDefnFactoryInternal)servLoc.GetInstance(); return posFactory.Create( guid, dataReader.GetNextRealHvo(), @@ -211,7 +208,7 @@ private static ICmAnnotationDefn AddAnnotationDefn(ICmPossibility owner, Guid gu var cache = owner.Cache; var servLoc = cache.ServiceLocator; var dataReader = (IDataReader)servLoc.GetInstance(); - var posFactory = servLoc.GetInstance() as ICmAnnotationDefnFactoryInternal; + var posFactory = (ICmAnnotationDefnFactoryInternal)servLoc.GetInstance(); return posFactory.Create( guid, dataReader.GetNextRealHvo(), @@ -271,7 +268,7 @@ private static void InitializeLexDb(ILangProject lp) AddMorphTypes(lexDb); - var listFactoryInternal = listFactory as ICmPossibilityListFactoryInternal; + var listFactoryInternal = (ICmPossibilityListFactoryInternal)listFactory; lexDb.ComplexEntryTypesOA = listFactoryInternal.Create( new Guid("1ee09905-63dd-4c7a-a9bd-1d496743ccd6"), dataReader.GetNextRealHvo()); @@ -305,7 +302,7 @@ private static void SetMinimalPublicationType(ILexDb lexDb) var wsMgr = servLoc.WritingSystemManager; var eng = wsMgr.UserWritingSystem.Handle; lexDb.PublicationTypesOA.Name.set_String(eng, "Publications"); - var possibilityFactory = servLoc.GetInstance() as ICmPossibilityFactoryInternal; + var possibilityFactory = (ICmPossibilityFactoryInternal)servLoc.GetInstance(); var dataReader = (IDataReader)servLoc.GetInstance(); var poss = possibilityFactory.Create( Guid.NewGuid(), @@ -324,7 +321,7 @@ private static void AddExtendedNoteTypes(ILexDb lexDb) var eng = servLoc.WritingSystemManager.UserWritingSystem; var typesList = lexDb.ExtendedNoteTypesOA; - var possibilityFactory = servLoc.GetInstance() as ICmPossibilityFactoryInternal; + var possibilityFactory = (ICmPossibilityFactoryInternal)servLoc.GetInstance(); for (var i = 1; i <= 5; i++) { var guid = Guid.Empty; @@ -520,7 +517,7 @@ private static void AddMorphTypes(ILexDb lexDb) var cache = lexDb.Cache; var servLoc = cache.ServiceLocator; var dataReader = (IDataReader)servLoc.GetInstance(); - var lexEntryTypeFactory = servLoc.GetInstance() as IMoMorphTypeFactoryInternal; + var lexEntryTypeFactory = (IMoMorphTypeFactoryInternal)servLoc.GetInstance(); var eng = servLoc.WritingSystemManager.UserWritingSystem; var morphTypesList = servLoc.GetInstance().Create(); diff --git a/src/SIL.LCModel/DomainServices/ConstraintFailure.cs b/src/SIL.LCModel/DomainServices/ConstraintFailure.cs index d2d43238..b7915530 100644 --- a/src/SIL.LCModel/DomainServices/ConstraintFailure.cs +++ b/src/SIL.LCModel/DomainServices/ConstraintFailure.cs @@ -183,8 +183,8 @@ public bool IsAnnotationCorrect() var text = existing.TextOA; if (text == null || text.ParagraphsOS.Count != 1) return false; - var para = text.ParagraphsOS[0] as IStTxtPara; - return para.Contents.Text == m_explanation; // we could get very picky and check the writing system etc, but I don't think it is necessary. + // we could get very picky and check the writing system etc, but I don't think it is necessary. + return text.ParagraphsOS[0] is IStTxtPara para && para.Contents.Text == m_explanation; } } } diff --git a/src/SIL.LCModel/DomainServices/CopyObject.cs b/src/SIL.LCModel/DomainServices/CopyObject.cs index 805a5929..19b97a8d 100644 --- a/src/SIL.LCModel/DomainServices/CopyObject.cs +++ b/src/SIL.LCModel/DomainServices/CopyObject.cs @@ -407,11 +407,13 @@ private TObj CreateOwnedObj(ICmObjectRepository srcRepository, TObj srcObj // Determine appropriate owner of copy // If source's owner has also been copied, we want to add this copy to the copy! // If a delegate has not been set, use the source's owner as the copy's owner. - ICmObject copied; - if (!m_sourceToCopyMap.TryGetValue(srcObj.Owner.Hvo, out copied)) + + if (!m_sourceToCopyMap.TryGetValue(srcObj.Owner.Hvo, out ICmObject copied)) copied = (m_topLevelOwnerFunct == kAddToSourceOwner) ? srcObj.Owner : null; Debug.Assert(copied != null, "Non top-level objects should have their owner already copied"); + if (copied == null) + throw new ArgumentNullException("srcObj", "Can't find copy of source object's owner in copy map. Non top-level objects should have their owner already copied."); int ord; switch (owningFlidType) diff --git a/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000010.cs b/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000010.cs index 933f6322..d3b88d61 100644 --- a/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000010.cs +++ b/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000010.cs @@ -2171,7 +2171,7 @@ private static XElement AddSegmentAnalyses( if (xficsForCurrentOldSegment.Count > 0) { foreach (var key in xficsForCurrentOldSegment.Keys) - xficsForCurrentPara.Remove(key); + xficsForCurrentPara!.Remove(key); // The one returned element is "Analyses" (or null, if no twfics/pfics). // It will have one, or more, 'objsur' type 'r' elements in it. diff --git a/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000017.cs b/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000017.cs index 22326b7e..c9749bf4 100644 --- a/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000017.cs +++ b/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000017.cs @@ -214,6 +214,10 @@ private void ConvertWeatherToCustomListAndField(IDomainObjectDTORepository repoD break; } } + + if (dtoWeatherList == null) + throw new NullReferenceException("repoDTO did not contain dtoWeatherList"); + dtoWeatherList.Xml = RemoveOwnerGuid(dtoWeatherList.Xml); repoDTO.Update(dtoWeatherList); diff --git a/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000019.cs b/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000019.cs index e77ba652..a63fb4bb 100644 --- a/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000019.cs +++ b/src/SIL.LCModel/DomainServices/DataMigration/DataMigration7000019.cs @@ -601,7 +601,8 @@ internal void Save(string filePath) private void WriteLdml(XmlWriter writer) { - Debug.Assert(writer != null); + if (writer == null) + throw new NullReferenceException("writer cannot be null."); writer.WriteStartElement("ldml"); WriteIdentityElement(writer); WriteLayoutElement(writer); diff --git a/src/SIL.LCModel/DomainServices/DataStoreInitializationServices.cs b/src/SIL.LCModel/DomainServices/DataStoreInitializationServices.cs index 2263ec8a..407ba61c 100644 --- a/src/SIL.LCModel/DomainServices/DataStoreInitializationServices.cs +++ b/src/SIL.LCModel/DomainServices/DataStoreInitializationServices.cs @@ -521,7 +521,7 @@ internal static void FixSegmentsForPara(IScrTxtPara para) { // The segment division is already in the correct location, so move on to the next // segment division. - if (!segCurr.IsLabel && segOldBaseLine.Text[0] == StringUtils.kChObject) + if (!segCurr.IsLabel && segOldBaseLine!.Text[0] == StringUtils.kChObject) { // The segment is only ORC(s) so copy the ORC(s) to the free translation // and, if needed, make puctuation forms for them. @@ -543,7 +543,7 @@ internal static void FixSegmentsForPara(IScrTxtPara para) bool fAppend = (iSegment > 0); // Always assume appending if not the first segment ISegment segDest = (fAppend) ? para.SegmentsOS[iSegment - 1] : para.SegmentsOS[iSegment + 1]; - if (segOldBaseLine.Text.Contains(StringUtils.kChObject)) + if (segOldBaseLine!.Text.Contains(StringUtils.kChObject)) { // The segment contains ORC(s), which need to be moved into the preceding or following segment. if (fAppend) @@ -574,7 +574,7 @@ internal static void FixSegmentsForPara(IScrTxtPara para) int iSegmentInsert = iSegment; Segment insertedSegment = (Segment)segFactory.Create(); para.SegmentsOS.Insert(iSegmentInsert, insertedSegment); - insertedSegment.BeginOffset = segExpected.IchMin; + insertedSegment.BeginOffset = segExpected!.IchMin; ITsString insertedSegBaseLine = insertedSegment.BaselineText; if (insertedSegBaseLine.Text[0] == StringUtils.kChObject) { diff --git a/src/SIL.LCModel/DomainServices/DomainObjectServices.cs b/src/SIL.LCModel/DomainServices/DomainObjectServices.cs index 2564e4bc..2811810f 100644 --- a/src/SIL.LCModel/DomainServices/DomainObjectServices.cs +++ b/src/SIL.LCModel/DomainServices/DomainObjectServices.cs @@ -2023,7 +2023,8 @@ public static IEnumerable GetObjectSet(ISilDataAccessManaged sda, /// public static IEnumerable GetVariantRefs(ILexEntry variantEntry) { - Debug.Assert(variantEntry != null, "Variant Entry shouldn't be null."); + if (variantEntry == null) + throw new NullReferenceException("variantEntry: Variant Entry shouldn't be null."); return from entryRef in variantEntry.EntryRefsOS where entryRef.RefType == LexEntryRefTags.krtVariant && // Is this necessary: entryRef.VariantEntryTypesRS != null && entryRef.VariantEntryTypesRS.Count > 0 && diff --git a/src/SIL.LCModel/DomainServices/ITextUtils.cs b/src/SIL.LCModel/DomainServices/ITextUtils.cs index e3b72f6d..342991e0 100644 --- a/src/SIL.LCModel/DomainServices/ITextUtils.cs +++ b/src/SIL.LCModel/DomainServices/ITextUtils.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Linq; using Icu; +using SIL.Extensions; using SIL.LCModel.Core.Cellar; using SIL.LCModel.Core.KernelInterfaces; using SIL.LCModel.Core.Scripture; @@ -537,7 +538,8 @@ private ITsString GetTssWffCandidate(ISilDataAccess sda, ITsString tssTxtWord, I /// internal IList CollectSegments(ITsString tssText, out List ichMinSegBreaks) { - Debug.Assert(m_para != null); + if (m_para == null) + throw new InvalidOperationException("Paragraph not initialized"); // Get the information we need to reuse existing annotations if possible. m_preExistingSegs.Clear(); m_preExistingSegs.AddRange(m_para.SegmentsOS); @@ -860,7 +862,8 @@ bool HasValidOffsets(int hvoAnnotation, int ichMin, int ichLim) /// static protected int IndexOfFirstUnusedId(List ids) { - Debug.Assert(ids != null); + if (ids == null) + throw new NullReferenceException("ids"); return IndexOfFirstUnusedId(ids.ToArray()); } @@ -1022,7 +1025,7 @@ bool TryReuseAnalysis(ITsString tssTxtWord, int ichMin, int ichLim, int ianalysi int iBestPossible = possibleIndices.IndexOf(iAnnClosest); int cRemove = iBestPossible + (fUsedBestPossible ? 1 : 0); if (cRemove > 0) - (possibleIndices as List).RemoveRange(0, cRemove); + ((List)possibleIndices).RemoveRange(0, cRemove); if (possibleIndices.Count == 0) { // remove its key from the Dictionary. @@ -1466,7 +1469,7 @@ internal bool MatchesWord(ITsString tssA, ITsString tssB) int lenA = tssA != null ? tssA.Length : 0; return tssB != null && lenA > 0 && lenA == tssB.Length && - (tssA.Equals(tssB) || + (tssA!.Equals(tssB) || (this.ToLower(tssA) == this.ToLower(tssB) && WordWs(tssA) == WordWs(tssB))); } diff --git a/src/SIL.LCModel/DomainServices/LcmStyleSheet.cs b/src/SIL.LCModel/DomainServices/LcmStyleSheet.cs index 24609013..6a8d8fe6 100644 --- a/src/SIL.LCModel/DomainServices/LcmStyleSheet.cs +++ b/src/SIL.LCModel/DomainServices/LcmStyleSheet.cs @@ -582,7 +582,6 @@ protected virtual int GetNewStyleHvo() /// ----------------------------------------------------------------------------------- public virtual void Delete(int hvoStyle) { - Debug.Assert(m_cache != null); m_ttpNormalFont = null; // may have been changed, recompute if needed. foreach (BaseStyleInfo styleInfo in m_StyleInfos) @@ -1064,7 +1063,9 @@ private void ComputeDerivedStyle(int cRecurLevel, BaseStyleInfo styleInfo) /// ----------------------------------------------------------------------------------- private ITsTextProps ComputeInheritance(ITsTextProps ttpBase, BaseStyleInfo styleInfo) { - Debug.Assert(ttpBase != null); + if (ttpBase == null) + throw new NullReferenceException("Base style properties are null"); + ITsTextProps ttpOverride = styleInfo.TextProps; if (ttpOverride == null) return ttpBase; diff --git a/src/SIL.LCModel/DomainServices/MorphServices.cs b/src/SIL.LCModel/DomainServices/MorphServices.cs index fe48bfa8..b935577e 100644 --- a/src/SIL.LCModel/DomainServices/MorphServices.cs +++ b/src/SIL.LCModel/DomainServices/MorphServices.cs @@ -301,6 +301,11 @@ public static IMoMorphType FindMorphType(LcmCache cache, ref string fullForm, ou Debug.Assert(cache != null); Debug.Assert(fullForm != null); + if (fullForm == null) + throw new NullReferenceException("fullForm"); + if (cache == null) + throw new NullReferenceException("cache"); + clsidForm = MoStemAllomorphTags.kClassId; // default IMoMorphType mt = null; fullForm = fullForm.Trim(); @@ -664,14 +669,14 @@ public static ILexSense GetMainOrFirstSenseOfVariant(ILexEntryRef variantRef) /// public static void GetMainEntryAndSenseStack(IVariantComponentLexeme mainEntryOrSense, out ILexEntry mainEntry, out ILexSense mainOrFirstSense) { - if (mainEntryOrSense is ILexEntry) + if (mainEntryOrSense is ILexEntry entry) { - mainEntry = mainEntryOrSense as ILexEntry; + mainEntry = entry; mainOrFirstSense = mainEntry.SensesOS.Count > 0 ? mainEntry.SensesOS[0] : null; } - else if (mainEntryOrSense is ILexSense) + else if (mainEntryOrSense is ILexSense sense) { - mainOrFirstSense = mainEntryOrSense as ILexSense; + mainOrFirstSense = sense; mainEntry = mainOrFirstSense.Entry; } else @@ -741,7 +746,7 @@ public static void JoinGlossAffixesOfInflVariantTypes(IEnumerable const string sSeparator = kDefaultSeparatorLexEntryInflTypeGlossAffix; foreach (var leit in variantEntryTypesRs.Where(let => (let as ILexEntryInflType) != null) - .Select(let => (let as ILexEntryInflType))) + .Select(let => (ILexEntryInflType)let)) { var cache = leit.Cache; var wsUser = cache.ServiceLocator.WritingSystemManager.UserWritingSystem; diff --git a/src/SIL.LCModel/DomainServices/ScrImportFileInfo.cs b/src/SIL.LCModel/DomainServices/ScrImportFileInfo.cs index 30453baa..667119da 100644 --- a/src/SIL.LCModel/DomainServices/ScrImportFileInfo.cs +++ b/src/SIL.LCModel/DomainServices/ScrImportFileInfo.cs @@ -683,7 +683,7 @@ protected void GetMappingsFromStream(TextReader reader) // save the chapter number as the last chapter and possibly the first // chapter number in the range. - if (currentRange.StartChapter == 0) + if (currentRange!.StartChapter == 0) currentRange.StartChapter = chapter; currentRange.EndChapter = chapter; } @@ -729,7 +729,7 @@ protected void GetMappingsFromStream(TextReader reader) if (firstVerse == -1) firstVerse = firstRef.Verse; } - else if (!markerMapping.IsExcluded && m_doStrictFileChecking && + else if (!markerMapping!.IsExcluded && m_doStrictFileChecking && markerMapping.MappingTarget == MappingTargetType.Figure) { // First, we need to consider whether any following lines also need @@ -782,7 +782,7 @@ protected void GetMappingsFromStream(TextReader reader) } } // Mark this mapping as "in-use" because it was found in the scanned file - markerMapping.SetIsInUse(m_domain, m_wsId, m_noteType, true); + markerMapping!.SetIsInUse(m_domain, m_wsId, m_noteType, true); if (m_scanInlineBackslashMarkers) lineIn = lineText; diff --git a/src/SIL.LCModel/DomainServices/ScrSfFileList.cs b/src/SIL.LCModel/DomainServices/ScrSfFileList.cs index 18849ebe..2b3a65ae 100644 --- a/src/SIL.LCModel/DomainServices/ScrSfFileList.cs +++ b/src/SIL.LCModel/DomainServices/ScrSfFileList.cs @@ -305,7 +305,7 @@ internal void CheckForOverlappingFilesInRange(ScrReference start, ScrReference e if (ScrImportFileInfo.CheckForOverlap(file1, file2)) { Debug.Assert(m_resolver != null, "Must set OverlappingFileResolver before calling CheckForOverlappingFilesInRange."); - removedList.Add(m_resolver.ChooseFileToRemove(file1, file2)); + removedList.Add(m_resolver!.ChooseFileToRemove(file1, file2)); } } } diff --git a/src/SIL.LCModel/DomainServices/StTxtParaBldr.cs b/src/SIL.LCModel/DomainServices/StTxtParaBldr.cs index 15035461..f8881937 100644 --- a/src/SIL.LCModel/DomainServices/StTxtParaBldr.cs +++ b/src/SIL.LCModel/DomainServices/StTxtParaBldr.cs @@ -43,8 +43,7 @@ public sealed class StTxtParaBldr /// ------------------------------------------------------------------------------------ public StTxtParaBldr(LcmCache cache) { - System.Diagnostics.Debug.Assert(cache != null); - m_cache = cache; + m_cache = cache ?? throw new ArgumentNullException("cache"); m_ParaStrBldr = TsStringUtils.MakeStrBldr(); @@ -167,7 +166,8 @@ public void AppendRun(string sRun, ITsTextProps props) // the props when the user begins to enter text in an empty para. if (sRun != string.Empty || Length == 0) { - System.Diagnostics.Debug.Assert(props != null); + if (props == null) + throw new NullReferenceException("TsTextProps is null"); int var; int ws = props.GetIntPropValues((int)FwTextPropType.ktptWs, out var); diff --git a/src/SIL.LCModel/FieldDescription.cs b/src/SIL.LCModel/FieldDescription.cs index 68fd23c8..5217f805 100644 --- a/src/SIL.LCModel/FieldDescription.cs +++ b/src/SIL.LCModel/FieldDescription.cs @@ -433,31 +433,29 @@ public int DataOccurrenceCount private bool DataNotNull(object o) { - if (o is CmObjectIdWithHvo) - o = (o as CmObjectIdWithHvo).GetObject(m_cache.ServiceLocator.GetInstance()); - if (o is MultiUnicodeAccessor) + if (o is CmObjectIdWithHvo obj) + o = obj.GetObject(m_cache.ServiceLocator.GetInstance()); + if (o is MultiUnicodeAccessor accessor) { - return (o as MultiUnicodeAccessor).StringCount > 0; + return accessor.StringCount > 0; } - else if (o is IStText) + else if (o is IStText txt) { - IStText txt = o as IStText; if (txt.ParagraphsOS.Count > 1) return true; - IStTxtPara para = txt.ParagraphsOS[0] as IStTxtPara; - return para != null && para.Contents != null && para.Contents.Length > 0; + return txt.ParagraphsOS[0] is IStTxtPara para && para.Contents != null && para.Contents.Length > 0; } - else if (o is LcmSet) + else if (o is LcmSet set) { - return (o as LcmSet).Count > 0; + return set.Count > 0; } - else if (o is GenDate) + else if (o is GenDate date) { - return !((GenDate)o).IsEmpty; + return !date.IsEmpty; } - else if (o is int) + else if (o is int v) { - return (int)o != 0; + return v != 0; } return true; } @@ -505,7 +503,8 @@ public static void ClearDataAbout() /// where each object in the array represents a row in the Field$ table. public static IEnumerable FieldDescriptors(LcmCache cache) { - Debug.Assert(cache != null); + if (cache == null) + return new List(); if (s_fieldDescriptors != null) return s_fieldDescriptors; diff --git a/src/SIL.LCModel/Infrastructure/Impl/ChangeReconciler.cs b/src/SIL.LCModel/Infrastructure/Impl/ChangeReconciler.cs index 86a83f13..2d410e33 100644 --- a/src/SIL.LCModel/Infrastructure/Impl/ChangeReconciler.cs +++ b/src/SIL.LCModel/Infrastructure/Impl/ChangeReconciler.cs @@ -880,7 +880,7 @@ where AttrValue(elt, "name") == name continue; var multiString = currentInternal.GetITsMultiStringProperty(flid); var oldValue = multiString.get_String(ws); - if ((tss == null && oldValue != null && oldValue.Length != 0) || !tss.Equals(oldValue)) + if ((tss == null && oldValue != null && oldValue.Length != 0) || (!tss?.Equals(oldValue) ?? false)) { if (processChangeRecord(new LcmMultiTsStringPropertyChanged(currentObj, flid, ws, oldValue, tss))) return; diff --git a/src/SIL.LCModel/Infrastructure/Impl/LcmStateChangingClasses.cs b/src/SIL.LCModel/Infrastructure/Impl/LcmStateChangingClasses.cs index 059d2fbe..254a9a54 100644 --- a/src/SIL.LCModel/Infrastructure/Impl/LcmStateChangingClasses.cs +++ b/src/SIL.LCModel/Infrastructure/Impl/LcmStateChangingClasses.cs @@ -1460,7 +1460,7 @@ protected override ChangeInformation ChangeInfo m_originalValue.Length); // Old value was not null, but new value is null - return new ChangeInformation(m_changedObject, m_modifiedFlid, 0, 0, m_originalValue.Length); + return new ChangeInformation(m_changedObject, m_modifiedFlid, 0, 0, m_originalValue!.Length); } } @@ -1743,7 +1743,7 @@ protected override ChangeInformation ChangeInfo return new ChangeInformation(m_changedObject, ModifiedFlid, 0, 0, 0); // Old value was not null, but new value is null - return new ChangeInformation(m_changedObject, ModifiedFlid, 0, 0, m_originalValue.Length); + return new ChangeInformation(m_changedObject, ModifiedFlid, 0, 0, m_originalValue!.Length); } } diff --git a/src/SIL.LCModel/Infrastructure/Impl/RepositoryAdditions.cs b/src/SIL.LCModel/Infrastructure/Impl/RepositoryAdditions.cs index 4585a42f..11108333 100644 --- a/src/SIL.LCModel/Infrastructure/Impl/RepositoryAdditions.cs +++ b/src/SIL.LCModel/Infrastructure/Impl/RepositoryAdditions.cs @@ -206,7 +206,7 @@ internal partial class CmObjectRepository : ICmObjectRepositoryInternal public int GetClsid(int hvo) { ICmObject obj = m_dataReader.GetObject(hvo); - Debug.Assert(obj != null, "We assume that GetObject will throw an exception if the object doesn't exist"); + // We assume that GetObject will throw an exception if the object doesn't exist return obj.ClassID; } @@ -370,7 +370,7 @@ public IEnumerable InstancesWithChartCellColumn(ICmPo SimpleBag chartCells = new SimpleBag(); foreach (IReferenceSource referrer in target.ReferringObjects) { - if ((referrer as CmObject).ClassID != 5123 /* "DsConstChart" */) + if (((CmObject)referrer).ClassID != 5123 /* "DsConstChart" */) { if (referrer.RefersTo(target, ConstituentChartCellPartTags.kflidColumn)) chartCells.Add(referrer.Source); @@ -1401,7 +1401,7 @@ List ILexEntryRepositoryInternal.CollectHomographs(string sForm, int if (fMatchLexForms) lexemeHomograph = StringServices.LexemeFormStatic(le); Debug.Assert(le != null); - if (le.Hvo != hvo && (homographForm == sForm || lexemeHomograph == sForm)) + if (le!.Hvo != hvo && (homographForm == sForm || lexemeHomograph == sForm)) { var types = le.MorphTypes; foreach (var mmt in types) @@ -1628,7 +1628,7 @@ internal partial class LexSenseRepository /// public IEnumerable InstancesWithSemanticDomain(ICmSemanticDomain domain) { - return (domain as CmSemanticDomain).ReferringSenses; + return ((CmSemanticDomain)domain).ReferringSenses; } /// @@ -1636,7 +1636,7 @@ public IEnumerable InstancesWithSemanticDomain(ICmSemanticDomain doma /// public IEnumerable InstancesWithReversalEntry(IReversalIndexEntry entry) { - return (entry as ReversalIndexEntry).SensesRS; + return ((ReversalIndexEntry)entry).SensesRS; } } #endregion diff --git a/src/SIL.LCModel/Infrastructure/Impl/SharedXMLBackendProvider.cs b/src/SIL.LCModel/Infrastructure/Impl/SharedXMLBackendProvider.cs index 69043417..65ece627 100644 --- a/src/SIL.LCModel/Infrastructure/Impl/SharedXMLBackendProvider.cs +++ b/src/SIL.LCModel/Infrastructure/Impl/SharedXMLBackendProvider.cs @@ -97,7 +97,7 @@ protected override int StartupInternal(int currentModelVersion) metadata = new CommitLogMetadata(); using (Process curProcess = Process.GetCurrentProcess()) - metadata.Peers[m_peerID] = new CommitLogPeer { ProcessID = curProcess.Id, Generation = metadata.FileGeneration }; + metadata!.Peers[m_peerID] = new CommitLogPeer { ProcessID = curProcess.Id, Generation = metadata.FileGeneration }; if (metadata.Master == Guid.Empty) { diff --git a/src/SIL.LCModel/Infrastructure/Impl/UnitOfWorkService.cs b/src/SIL.LCModel/Infrastructure/Impl/UnitOfWorkService.cs index 45f1b966..d54ee933 100644 --- a/src/SIL.LCModel/Infrastructure/Impl/UnitOfWorkService.cs +++ b/src/SIL.LCModel/Infrastructure/Impl/UnitOfWorkService.cs @@ -403,7 +403,7 @@ private void RevertToSavedState() } } } - if (mostRecentUnsavedChange == null) + if (mostRecentUnsavedChange == null || stackWithMostRecentChange == null) break; stackWithMostRecentChange.RevertUnsavedUnitOfWork(); if (!updatedStacks.Contains(stackWithMostRecentChange)) diff --git a/src/SIL.LCModel/SIL.LCModel.csproj b/src/SIL.LCModel/SIL.LCModel.csproj index 3e74509d..931f0a61 100644 --- a/src/SIL.LCModel/SIL.LCModel.csproj +++ b/src/SIL.LCModel/SIL.LCModel.csproj @@ -27,6 +27,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/tests/SIL.LCModel.Core.Tests/SIL.LCModel.Core.Tests.csproj b/tests/SIL.LCModel.Core.Tests/SIL.LCModel.Core.Tests.csproj index 93be06eb..9e8f73f0 100644 --- a/tests/SIL.LCModel.Core.Tests/SIL.LCModel.Core.Tests.csproj +++ b/tests/SIL.LCModel.Core.Tests/SIL.LCModel.Core.Tests.csproj @@ -6,6 +6,7 @@ The liblcm library is the core FieldWorks model for linguistic analyses of languages. Tools in this library provide the ability to store and interact with language and culture data, including anthropological, text corpus, and linguistics data. This package provides unit tests for SIL.LCModel.Core. true + disable diff --git a/tests/SIL.LCModel.Core.Tests/WritingSystems/CoreWritingSystemDefinitionTests.cs b/tests/SIL.LCModel.Core.Tests/WritingSystems/CoreWritingSystemDefinitionTests.cs index fbaaea6a..565779fa 100644 --- a/tests/SIL.LCModel.Core.Tests/WritingSystems/CoreWritingSystemDefinitionTests.cs +++ b/tests/SIL.LCModel.Core.Tests/WritingSystems/CoreWritingSystemDefinitionTests.cs @@ -42,7 +42,7 @@ public void CopyCopiesAllNeededMembers() CoreWritingSystemDefinition copyable = CreateNewCloneable(); MethodInfo getAllFields = null; var type = GetType().BaseType; - while(getAllFields == null && type != null) + while(getAllFields == null) { getAllFields = type.GetMethod("GetAllFields", BindingFlags.NonPublic | BindingFlags.Static); type = type.BaseType; diff --git a/tests/SIL.LCModel.FixData.Tests/SIL.LCModel.FixData.Tests.csproj b/tests/SIL.LCModel.FixData.Tests/SIL.LCModel.FixData.Tests.csproj index 98038ba9..4b490cf7 100644 --- a/tests/SIL.LCModel.FixData.Tests/SIL.LCModel.FixData.Tests.csproj +++ b/tests/SIL.LCModel.FixData.Tests/SIL.LCModel.FixData.Tests.csproj @@ -4,6 +4,7 @@ net461;net8.0 SIL.LCModel.FixData false + disable diff --git a/tests/SIL.LCModel.Tests/SIL.LCModel.Tests.csproj b/tests/SIL.LCModel.Tests/SIL.LCModel.Tests.csproj index 9353e879..db1bfbe1 100644 --- a/tests/SIL.LCModel.Tests/SIL.LCModel.Tests.csproj +++ b/tests/SIL.LCModel.Tests/SIL.LCModel.Tests.csproj @@ -6,6 +6,7 @@ The liblcm library is the core FieldWorks model for linguistic analyses of languages. Tools in this library provide the ability to store and interact with language and culture data, including anthropological, text corpus, and linguistics data. This package provides unit tests for SIL.LCModel. true + disable diff --git a/tests/SIL.LCModel.Utils.Tests/SIL.LCModel.Utils.Tests.csproj b/tests/SIL.LCModel.Utils.Tests/SIL.LCModel.Utils.Tests.csproj index ca1b2a25..ae102158 100644 --- a/tests/SIL.LCModel.Utils.Tests/SIL.LCModel.Utils.Tests.csproj +++ b/tests/SIL.LCModel.Utils.Tests/SIL.LCModel.Utils.Tests.csproj @@ -6,6 +6,7 @@ The liblcm library is the core FieldWorks model for linguistic analyses of languages. Tools in this library provide the ability to store and interact with language and culture data, including anthropological, text corpus, and linguistics data. This package provides unit tests for SIL.LCModel.Utils and test utility classes true + disable diff --git a/tests/TestHelper/TestHelper.csproj b/tests/TestHelper/TestHelper.csproj index 2d9aa817..9cb56ffc 100644 --- a/tests/TestHelper/TestHelper.csproj +++ b/tests/TestHelper/TestHelper.csproj @@ -7,6 +7,7 @@ false Exe false + disable