Browse Source

more CS8600 cleanup

pull/3287/head
apmoskevitz 9 months ago
parent
commit
eae6e21ee5
  1. 2
      ICSharpCode.BamlDecompiler/Baml/BamlContext.cs
  2. 2
      ICSharpCode.BamlDecompiler/Baml/BamlNode.cs
  3. 2
      ICSharpCode.BamlDecompiler/Baml/BamlReader.cs
  4. 2
      ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs
  5. 2
      ICSharpCode.BamlDecompiler/Xaml/XamlType.cs
  6. 2
      ICSharpCode.BamlDecompiler/XamlContext.cs
  7. 2
      ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs
  8. 5
      ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs
  9. 4
      ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs
  10. 4
      ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs
  11. 6
      ILSpy.ReadyToRun/ReadyToRunDisassembler.cs
  12. 10
      ILSpy.ReadyToRun/ReadyToRunLanguage.cs
  13. 4
      ILSpy/AboutPage.cs
  14. 2
      ILSpy/Analyzers/AnalyzerEntityTreeNode.cs
  15. 4
      ILSpy/Analyzers/AnalyzerRootNode.cs
  16. 2
      ILSpy/Analyzers/AnalyzerTreeViewModel.cs
  17. 8
      ILSpy/App.xaml.cs
  18. 4
      ILSpy/AvalonEdit/TextMarkerService.cs
  19. 2
      ILSpy/Commands/CommandWrapper.cs
  20. 2
      ILSpy/Commands/DecompileAllCommand.cs
  21. 2
      ILSpy/Commands/DecompileCommand.cs
  22. 2
      ILSpy/Commands/DisassembleAllCommand.cs
  23. 4
      ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs
  24. 9
      ILSpy/Commands/SaveCodeContextMenuEntry.cs
  25. 2
      ILSpy/Commands/ScopeSearchToNamespace.cs
  26. 2
      ILSpy/Commands/SelectPdbContextMenuEntry.cs
  27. 24
      ILSpy/ContextMenuEntry.cs
  28. 10
      ILSpy/Controls/GridViewColumnAutoSize.cs
  29. 2
      ILSpy/Controls/SearchBox.cs
  30. 12
      ILSpy/Controls/SortableGridViewColumn.cs
  31. 20
      ILSpy/Controls/TreeView/SharpTreeView.cs
  32. 2
      ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs
  33. 4
      ILSpy/Controls/ZoomScrollViewer.cs
  34. 4
      ILSpy/Docking/DockWorkspace.cs
  35. 2
      ILSpy/ISmartTextOutput.cs
  36. 16
      ILSpy/Images/Images.cs
  37. 8
      ILSpy/Languages/CSharpHighlightingTokenWriter.cs
  38. 18
      ILSpy/Languages/CSharpLanguage.cs
  39. 14
      ILSpy/Languages/ILLanguage.cs
  40. 2
      ILSpy/Languages/Language.cs
  41. 40
      ILSpy/MainWindow.xaml.cs
  42. 2
      ILSpy/Metadata/CorTables/EventTableTreeNode.cs
  43. 2
      ILSpy/Metadata/CorTables/FieldTableTreeNode.cs
  44. 2
      ILSpy/Metadata/CorTables/MethodTableTreeNode.cs
  45. 2
      ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs
  46. 2
      ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs
  47. 2
      ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs
  48. 4
      ILSpy/Metadata/GoToTokenCommand.cs
  49. 2
      ILSpy/NavigationState.cs
  50. 4
      ILSpy/Options/DisplaySettingsPanel.xaml.cs
  51. 4
      ILSpy/Options/OptionsDialog.xaml.cs
  52. 10
      ILSpy/Search/SearchPane.xaml.cs
  53. 12
      ILSpy/SessionSettings.cs
  54. 2
      ILSpy/TaskHelper.cs
  55. 2
      ILSpy/TextView/AvalonEditTextOutput.cs
  56. 6
      ILSpy/TextView/DecompilerTextView.cs
  57. 6
      ILSpy/TextView/DocumentationUIBuilder.cs
  58. 6
      ILSpy/TextView/FoldingCommands.cs
  59. 16
      ILSpy/TreeNodes/AssemblyListTreeNode.cs
  60. 8
      ILSpy/TreeNodes/AssemblyTreeNode.cs
  61. 6
      ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs
  62. 8
      ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs
  63. 2
      ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs
  64. 2
      ILSpy/TreeNodes/ThreadingSupport.cs
  65. 2
      ILSpy/Updates/NotifyOfUpdatesStrategy.cs
  66. 2
      TestPlugin/CustomLanguage.cs
  67. 2
      TestPlugin/CustomOptionPage.xaml.cs

2
ICSharpCode.BamlDecompiler/Baml/BamlContext.cs

@ -116,7 +116,7 @@ namespace ICSharpCode.BamlDecompiler.Baml
private IModule FindMatchingReference(AssemblyNameReference name) private IModule FindMatchingReference(AssemblyNameReference name)
{ {
IModule bestMatch = null; IModule? bestMatch = null;
foreach (var module in TypeSystem.ReferencedModules) foreach (var module in TypeSystem.ReferencedModules)
{ {
if (module.AssemblyName == name.Name) if (module.AssemblyName == name.Name)

2
ICSharpCode.BamlDecompiler/Baml/BamlNode.cs

@ -111,7 +111,7 @@ namespace ICSharpCode.BamlDecompiler.Baml
{ {
Debug.Assert(document.Count > 0 && document[0].Type == BamlRecordType.DocumentStart); Debug.Assert(document.Count > 0 && document[0].Type == BamlRecordType.DocumentStart);
BamlBlockNode current = null; BamlBlockNode? current = null;
var stack = new Stack<BamlBlockNode>(); var stack = new Stack<BamlBlockNode>();
for (int i = 0; i < document.Count; i++) for (int i = 0; i < document.Count; i++)

2
ICSharpCode.BamlDecompiler/Baml/BamlReader.cs

@ -91,7 +91,7 @@ namespace ICSharpCode.BamlDecompiler.Baml
long pos = str.Position; long pos = str.Position;
var type = (BamlRecordType)reader.ReadByte(); var type = (BamlRecordType)reader.ReadByte();
BamlRecord rec = null; BamlRecord? rec = null;
switch (type) switch (type)
{ {
case BamlRecordType.AssemblyInfo: case BamlRecordType.AssemblyInfo:

2
ICSharpCode.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs

@ -127,7 +127,7 @@ namespace ICSharpCode.BamlDecompiler.Rewrite
return; return;
var connect = connectorInterface.GetMethods(m => m.Name == "Connect").SingleOrDefault(); var connect = connectorInterface.GetMethods(m => m.Name == "Connect").SingleOrDefault();
IMethod connectMethod = null; IMethod? connectMethod = null;
MethodDefinition connectMetadataEntry = default; MethodDefinition connectMetadataEntry = default;
var module = ctx.TypeSystem.MainModule.MetadataFile; var module = ctx.TypeSystem.MainModule.MetadataFile;

2
ICSharpCode.BamlDecompiler/Xaml/XamlType.cs

@ -62,7 +62,7 @@ namespace ICSharpCode.BamlDecompiler.Xaml
// Since XmlnsProperty records are inside the element, // Since XmlnsProperty records are inside the element,
// the namespace is resolved after processing the element body. // the namespace is resolved after processing the element body.
string xmlNs = null; string? xmlNs = null;
if (elem.Annotation<XmlnsScope>() != null) if (elem.Annotation<XmlnsScope>() != null)
xmlNs = elem.Annotation<XmlnsScope>().LookupXmlns(FullAssemblyName, TypeNamespace); xmlNs = elem.Annotation<XmlnsScope>().LookupXmlns(FullAssemblyName, TypeNamespace);
if (xmlNs == null) if (xmlNs == null)

2
ICSharpCode.BamlDecompiler/XamlContext.cs

@ -143,7 +143,7 @@ namespace ICSharpCode.BamlDecompiler
XamlType type; XamlType type;
string name; string name;
IMember member; IMember? member;
if (id > 0x7fff) if (id > 0x7fff)
{ {

2
ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs

@ -499,7 +499,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
foreach (char ch in str) foreach (char ch in str)
{ {
string s = ch == '"' ? "\\\"" : ConvertChar(ch); string? s = ch == '"' ? "\\\"" : ConvertChar(ch);
if (s != null) if (s != null)
sb.Append(s); sb.Append(s);
else else

5
ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs

@ -17,6 +17,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Diagnostics.CodeAnalysis;
namespace ICSharpCode.Decompiler.Util namespace ICSharpCode.Decompiler.Util
{ {
@ -34,7 +35,9 @@ namespace ICSharpCode.Decompiler.Util
/// </summary> /// </summary>
/// <exception cref="OverflowException">Overflow checking is enabled and an overflow occurred.</exception> /// <exception cref="OverflowException">Overflow checking is enabled and an overflow occurred.</exception>
/// <exception cref="InvalidCastException">The cast is invalid, e.g. casting a boolean to an integer.</exception> /// <exception cref="InvalidCastException">The cast is invalid, e.g. casting a boolean to an integer.</exception>
public static object? Cast(TypeCode targetType, object input, bool checkForOverflow) //[return: MaybeNull]
//[return: NotNullIfNotNull(nameof(input))]
public static object Cast(TypeCode targetType, [MaybeNull] object input, bool checkForOverflow)
{ {
if (input == null) if (input == null)
return null; return null;

4
ICSharpCode.ILSpyCmd/IlspyCmdProgram.cs

@ -122,7 +122,7 @@ Examples:
private async Task<int> OnExecuteAsync(CommandLineApplication app) private async Task<int> OnExecuteAsync(CommandLineApplication app)
{ {
Task<PackageCheckResult> updateCheckTask = null; Task<PackageCheckResult>? updateCheckTask = null;
if (!DisableUpdateCheck) if (!DisableUpdateCheck)
{ {
updateCheckTask = DotNetToolUpdateChecker.CheckForPackageUpdateAsync("ilspycmd"); updateCheckTask = DotNetToolUpdateChecker.CheckForPackageUpdateAsync("ilspycmd");
@ -214,7 +214,7 @@ Examples:
} }
else if (CreateDebugInfoFlag) else if (CreateDebugInfoFlag)
{ {
string pdbFileName = null; string? pdbFileName = null;
if (outputDirectory != null) if (outputDirectory != null)
{ {
string outputName = Path.GetFileNameWithoutExtension(fileName); string outputName = Path.GetFileNameWithoutExtension(fileName);

4
ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs

@ -205,11 +205,11 @@ namespace ILSpy.BamlDecompiler.Tests
return line.Trim(); return line.Trim();
} }
Stream LoadBaml(Resource res, string name) Stream? LoadBaml(Resource res, string name)
{ {
if (res.ResourceType != ResourceType.Embedded) if (res.ResourceType != ResourceType.Embedded)
return null; return null;
Stream s = res.TryOpenStream(); Stream? s = res.TryOpenStream();
if (s == null) if (s == null)
return null; return null;
s.Position = 0; s.Position = 0;

6
ILSpy.ReadyToRun/ReadyToRunDisassembler.cs

@ -67,14 +67,14 @@ namespace ICSharpCode.ILSpy.ReadyToRun
} }
} }
Dictionary<ulong, UnwindCode> unwindInfo = null; Dictionary<ulong, UnwindCode>? unwindInfo = null;
if (ReadyToRunOptions.GetIsShowUnwindInfo(null) && bitness == 64) if (ReadyToRunOptions.GetIsShowUnwindInfo(null) && bitness == 64)
{ {
unwindInfo = WriteUnwindInfo(); unwindInfo = WriteUnwindInfo();
} }
bool isShowDebugInfo = ReadyToRunOptions.GetIsShowDebugInfo(null); bool isShowDebugInfo = ReadyToRunOptions.GetIsShowDebugInfo(null);
DebugInfoHelper debugInfo = null; DebugInfoHelper? debugInfo = null;
if (isShowDebugInfo) if (isShowDebugInfo)
{ {
debugInfo = WriteDebugInfo(); debugInfo = WriteDebugInfo();
@ -98,7 +98,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun
} }
string disassemblyFormat = ReadyToRunOptions.GetDisassemblyFormat(null); string disassemblyFormat = ReadyToRunOptions.GetDisassemblyFormat(null);
Formatter formatter = null; Formatter? formatter = null;
if (disassemblyFormat.Equals(ReadyToRunOptions.intel)) if (disassemblyFormat.Equals(ReadyToRunOptions.intel))
{ {
formatter = new NasmFormatter(); formatter = new NasmFormatter();

10
ILSpy.ReadyToRun/ReadyToRunLanguage.cs

@ -114,7 +114,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun
public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
{ {
PEFile module = assembly.GetMetadataFileAsync().GetAwaiter().GetResult() as PEFile; PEFile? module = assembly.GetMetadataFileAsync().GetAwaiter().GetResult() as PEFile;
ReadyToRunReaderCacheEntry cacheEntry = GetReader(assembly, module); ReadyToRunReaderCacheEntry cacheEntry = GetReader(assembly, module);
if (cacheEntry.readyToRunReader == null) if (cacheEntry.readyToRunReader == null)
{ {
@ -137,7 +137,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun
public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
{ {
PEFile module = method.ParentModule.MetadataFile as PEFile; PEFile? module = method.ParentModule.MetadataFile as PEFile;
ReadyToRunReaderCacheEntry cacheEntry = GetReader(module.GetLoadedAssembly(), module); ReadyToRunReaderCacheEntry cacheEntry = GetReader(module.GetLoadedAssembly(), module);
if (cacheEntry.readyToRunReader == null) if (cacheEntry.readyToRunReader == null)
{ {
@ -158,7 +158,7 @@ namespace ICSharpCode.ILSpy.ReadyToRun
} }
if (cacheEntry.methodMap == null) if (cacheEntry.methodMap == null)
{ {
IEnumerable<ReadyToRunMethod> readyToRunMethods = null; IEnumerable<ReadyToRunMethod>? readyToRunMethods = null;
if (cacheEntry.compositeReadyToRunReader == null) if (cacheEntry.compositeReadyToRunReader == null)
{ {
readyToRunMethods = reader.Methods; readyToRunMethods = reader.Methods;
@ -192,8 +192,8 @@ namespace ICSharpCode.ILSpy.ReadyToRun
#endif #endif
foreach (RuntimeFunction runtimeFunction in readyToRunMethod.RuntimeFunctions) foreach (RuntimeFunction runtimeFunction in readyToRunMethod.RuntimeFunctions)
{ {
PEFile file = null; PEFile? file = null;
ReadyToRunReader disassemblingReader = null; ReadyToRunReader? disassemblingReader = null;
if (cacheEntry.compositeReadyToRunReader == null) if (cacheEntry.compositeReadyToRunReader == null)
{ {
disassemblingReader = reader; disassemblingReader = reader;

4
ILSpy/AboutPage.cs

@ -90,11 +90,11 @@ namespace ICSharpCode.ILSpy
plugin.Write(output); plugin.Write(output);
output.WriteLine(); output.WriteLine();
output.Address = new Uri("resource://AboutPage"); output.Address = new Uri("resource://AboutPage");
using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), Resources.ILSpyAboutPageTxt)) using (Stream? s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), Resources.ILSpyAboutPageTxt))
{ {
using (StreamReader r = new StreamReader(s)) using (StreamReader r = new StreamReader(s))
{ {
string line; string? line;
while ((line = r.ReadLine()) != null) while ((line = r.ReadLine()) != null)
{ {
output.WriteLine(line); output.WriteLine(line);

2
ILSpy/Analyzers/AnalyzerEntityTreeNode.cs

@ -54,7 +54,7 @@ namespace ICSharpCode.ILSpy.Analyzers
} }
this.Children.RemoveAll( this.Children.RemoveAll(
delegate (SharpTreeNode n) { delegate (SharpTreeNode n) {
AnalyzerTreeNode an = n as AnalyzerTreeNode; AnalyzerTreeNode? an = n as AnalyzerTreeNode;
return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies); return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies);
}); });
return true; return true;

4
ILSpy/Analyzers/AnalyzerRootNode.cs

@ -15,7 +15,7 @@ public sealed class AnalyzerRootNode : AnalyzerTreeNode
MessageBus<CurrentAssemblyListChangedEventArgs>.Subscribers += (sender, e) => CurrentAssemblyList_Changed(sender, e); MessageBus<CurrentAssemblyListChangedEventArgs>.Subscribers += (sender, e) => CurrentAssemblyList_Changed(sender, e);
} }
void CurrentAssemblyList_Changed(object sender, NotifyCollectionChangedEventArgs e) void CurrentAssemblyList_Changed(object? sender, NotifyCollectionChangedEventArgs e)
{ {
if (e.Action == NotifyCollectionChangedAction.Reset) if (e.Action == NotifyCollectionChangedAction.Reset)
{ {
@ -34,7 +34,7 @@ public sealed class AnalyzerRootNode : AnalyzerTreeNode
{ {
this.Children.RemoveAll( this.Children.RemoveAll(
delegate (SharpTreeNode n) { delegate (SharpTreeNode n) {
AnalyzerTreeNode an = n as AnalyzerTreeNode; AnalyzerTreeNode? an = n as AnalyzerTreeNode;
return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies); return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies);
}); });
return true; return true;

2
ILSpy/Analyzers/AnalyzerTreeViewModel.cs

@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy.Analyzers
{ {
Show(); Show();
AnalyzerTreeNode target = default; AnalyzerTreeNode? target = default;
if (node is AnalyzerEntityTreeNode { Member: { } member }) if (node is AnalyzerEntityTreeNode { Member: { } member })
{ {

8
ILSpy/App.xaml.cs

@ -224,7 +224,7 @@ namespace ICSharpCode.ILSpy
static void ShowErrorBox(object sender, UnhandledExceptionEventArgs e) static void ShowErrorBox(object sender, UnhandledExceptionEventArgs e)
{ {
Exception ex = e.ExceptionObject as Exception; Exception? ex = e.ExceptionObject as Exception;
if (ex != null) if (ex != null)
{ {
UnhandledException(ex); UnhandledException(ex);
@ -237,13 +237,13 @@ namespace ICSharpCode.ILSpy
internal static void UnhandledException(Exception exception) internal static void UnhandledException(Exception exception)
{ {
Debug.WriteLine(exception.ToString()); Debug.WriteLine(exception.ToString());
for (Exception ex = exception; ex != null; ex = ex.InnerException) for (Exception? ex = exception; ex != null; ex = ex.InnerException)
{ {
ReflectionTypeLoadException rtle = ex as ReflectionTypeLoadException; ReflectionTypeLoadException? rtle = ex as ReflectionTypeLoadException;
if (rtle != null && rtle.LoaderExceptions.Length > 0) if (rtle != null && rtle.LoaderExceptions.Length > 0)
{ {
exception = rtle.LoaderExceptions[0]; exception = rtle.LoaderExceptions[0];
Debug.WriteLine(exception.ToString()); Debug.WriteLine(exception?.ToString());
break; break;
} }
} }

4
ILSpy/AvalonEdit/TextMarkerService.cs

@ -102,7 +102,7 @@ namespace ICSharpCode.ILSpy.AvalonEdit
{ {
if (marker == null) if (marker == null)
throw new ArgumentNullException(nameof(marker)); throw new ArgumentNullException(nameof(marker));
TextMarker m = marker as TextMarker; TextMarker? m = marker as TextMarker;
if (markers != null && markers.Remove(m)) if (markers != null && markers.Remove(m))
{ {
Redraw(m); Redraw(m);
@ -131,7 +131,7 @@ namespace ICSharpCode.ILSpy.AvalonEdit
int lineEnd = lineStart + line.Length; int lineEnd = lineStart + line.Length;
foreach (TextMarker marker in markers.FindOverlappingSegments(lineStart, line.Length)) foreach (TextMarker marker in markers.FindOverlappingSegments(lineStart, line.Length))
{ {
Brush foregroundBrush = null; Brush? foregroundBrush = null;
if (marker.ForegroundColor != null) if (marker.ForegroundColor != null)
{ {
foregroundBrush = new SolidColorBrush(marker.ForegroundColor.Value); foregroundBrush = new SolidColorBrush(marker.ForegroundColor.Value);

2
ILSpy/Commands/CommandWrapper.cs

@ -32,7 +32,7 @@ namespace ICSharpCode.ILSpy
public static ICommand Unwrap(ICommand command) public static ICommand Unwrap(ICommand command)
{ {
CommandWrapper w = command as CommandWrapper; CommandWrapper? w = command as CommandWrapper;
if (w != null) if (w != null)
return w.wrappedCommand; return w.wrappedCommand;
else else

2
ILSpy/Commands/DecompileAllCommand.cs

@ -55,7 +55,7 @@ namespace ICSharpCode.ILSpy
if (!asm.HasLoadError) if (!asm.HasLoadError)
{ {
Stopwatch w = Stopwatch.StartNew(); Stopwatch w = Stopwatch.StartNew();
Exception exception = null; Exception? exception = null;
using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs"))
{ {
try try

2
ILSpy/Commands/DecompileCommand.cs

@ -56,7 +56,7 @@ namespace ICSharpCode.ILSpy.Commands
public void Execute(TextViewContext context) public void Execute(TextViewContext context)
{ {
IEntity selection = null; IEntity? selection = null;
if (context.SelectedTreeNodes?[0] is IMemberTreeNode node) if (context.SelectedTreeNodes?[0] is IMemberTreeNode node)
{ {
selection = node.Member; selection = node.Member;

2
ILSpy/Commands/DisassembleAllCommand.cs

@ -50,7 +50,7 @@ namespace ICSharpCode.ILSpy
if (!asm.HasLoadError) if (!asm.HasLoadError)
{ {
Stopwatch w = Stopwatch.StartNew(); Stopwatch w = Stopwatch.StartNew();
Exception exception = null; Exception? exception = null;
using (var writer = new System.IO.StreamWriter("c:\\temp\\disassembled\\" + asm.Text.Replace("(", "").Replace(")", "").Replace(' ', '_') + ".il")) using (var writer = new System.IO.StreamWriter("c:\\temp\\disassembled\\" + asm.Text.Replace("(", "").Replace(")", "").Replace(' ', '_') + ".il"))
{ {
try try

4
ILSpy/Commands/ExtractPackageEntryContextMenuEntry.cs

@ -57,7 +57,7 @@ namespace ICSharpCode.ILSpy
return; return;
string fileName = dlg.FileName; string fileName = dlg.FileName;
string outputFolderOrFileName = fileName; string? outputFolderOrFileName = fileName;
if (selectedNodes.Length > 1) if (selectedNodes.Length > 1)
outputFolderOrFileName = Path.GetDirectoryName(outputFolderOrFileName); outputFolderOrFileName = Path.GetDirectoryName(outputFolderOrFileName);
@ -89,7 +89,7 @@ namespace ICSharpCode.ILSpy
void SaveEntry(ITextOutput output, PackageEntry entry, string targetFileName) void SaveEntry(ITextOutput output, PackageEntry entry, string targetFileName)
{ {
output.Write(entry.Name + ": "); output.Write(entry.Name + ": ");
using Stream stream = entry.TryOpenStream(); using Stream? stream = entry.TryOpenStream();
if (stream == null) if (stream == null)
{ {
output.WriteLine("Could not open stream!"); output.WriteLine("Could not open stream!");

9
ILSpy/Commands/SaveCodeContextMenuEntry.cs

@ -18,6 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
@ -26,13 +27,11 @@ using ICSharpCode.Decompiler.IL;
using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpy.Options;
using ICSharpCode.ILSpy.Properties; using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpy.Util;
using ICSharpCode.ILSpy.ViewModels; using ICSharpCode.ILSpy.ViewModels;
using Microsoft.Win32;
using ICSharpCode.ILSpyX.TreeView; using ICSharpCode.ILSpyX.TreeView;
using System.ComponentModel.Composition;
using ICSharpCode.ILSpy.Util; using Microsoft.Win32;
namespace ICSharpCode.ILSpy.TextView namespace ICSharpCode.ILSpy.TextView
{ {
@ -112,7 +111,7 @@ namespace ICSharpCode.ILSpy.TextView
return null; return null;
} }
string selectedPath = Path.GetDirectoryName(dlg.FileName); string? selectedPath = Path.GetDirectoryName(dlg.FileName);
bool directoryNotEmpty; bool directoryNotEmpty;
try try
{ {

2
ILSpy/Commands/ScopeSearchToNamespace.cs

@ -41,7 +41,7 @@ namespace ICSharpCode.ILSpy
public void Execute(TextViewContext context) public void Execute(TextViewContext context)
{ {
string ns = GetNamespace(context); string ns = GetNamespace(context);
string searchTerm = searchPane.SearchTerm; string? searchTerm = searchPane.SearchTerm;
string[] args = CommandLineTools.CommandLineToArgumentArray(searchTerm); string[] args = CommandLineTools.CommandLineToArgumentArray(searchTerm);
bool replaced = false; bool replaced = false;
for (int i = 0; i < args.Length; i++) for (int i = 0; i < args.Length; i++)

2
ILSpy/Commands/SelectPdbContextMenuEntry.cs

@ -48,7 +48,7 @@ namespace ICSharpCode.ILSpy
await assembly.LoadDebugInfo(dlg.FileName); await assembly.LoadDebugInfo(dlg.FileName);
} }
var node = (AssemblyTreeNode)MainWindow.Instance.FindNodeByPath(new[] { assembly.FileName }, true); var node = (AssemblyTreeNode?)MainWindow.Instance.FindNodeByPath(new[] { assembly.FileName }, true);
node.UpdateToolTip(); node.UpdateToolTip();
MainWindow.Instance.SelectNode(node); MainWindow.Instance.SelectNode(node);
MainWindow.Instance.RefreshDecompiledView(); MainWindow.Instance.RefreshDecompiledView();

24
ILSpy/ContextMenuEntry.cs

@ -26,9 +26,9 @@ using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using ICSharpCode.AvalonEdit; using ICSharpCode.AvalonEdit;
using ICSharpCode.ILSpy.Controls.TreeView;
using ICSharpCode.ILSpy.TextView; using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpyX.Search; using ICSharpCode.ILSpyX.Search;
using ICSharpCode.ILSpy.Controls.TreeView;
using ICSharpCode.ILSpyX.TreeView; using ICSharpCode.ILSpyX.TreeView;
using TomsToolbox.Composition; using TomsToolbox.Composition;
@ -48,37 +48,37 @@ namespace ICSharpCode.ILSpy
/// Returns the selected nodes in the tree view. /// Returns the selected nodes in the tree view.
/// Returns null, if context menu does not belong to a tree view. /// Returns null, if context menu does not belong to a tree view.
/// </summary> /// </summary>
public SharpTreeNode[] SelectedTreeNodes { get; private set; } public SharpTreeNode[]? SelectedTreeNodes { get; private set; }
/// <summary> /// <summary>
/// Returns the tree view the context menu is assigned to. /// Returns the tree view the context menu is assigned to.
/// Returns null, if context menu is not assigned to a tree view. /// Returns null, if context menu is not assigned to a tree view.
/// </summary> /// </summary>
public SharpTreeView TreeView { get; private set; } public SharpTreeView? TreeView { get; private set; }
/// <summary> /// <summary>
/// Returns the text view the context menu is assigned to. /// Returns the text view the context menu is assigned to.
/// Returns null, if context menu is not assigned to a text view. /// Returns null, if context menu is not assigned to a text view.
/// </summary> /// </summary>
public DecompilerTextView TextView { get; private set; } public DecompilerTextView? TextView { get; private set; }
/// <summary> /// <summary>
/// Returns the list box the context menu is assigned to. /// Returns the list box the context menu is assigned to.
/// Returns null, if context menu is not assigned to a list box. /// Returns null, if context menu is not assigned to a list box.
/// </summary> /// </summary>
public ListBox ListBox { get; private set; } public ListBox? ListBox { get; private set; }
/// <summary> /// <summary>
/// Returns the data grid the context menu is assigned to. /// Returns the data grid the context menu is assigned to.
/// Returns null, if context menu is not assigned to a data grid. /// Returns null, if context menu is not assigned to a data grid.
/// </summary> /// </summary>
public DataGrid DataGrid { get; private set; } public DataGrid? DataGrid { get; private set; }
/// <summary> /// <summary>
/// Returns the reference the mouse cursor is currently hovering above. /// Returns the reference the mouse cursor is currently hovering above.
/// Returns null, if there was no reference found. /// Returns null, if there was no reference found.
/// </summary> /// </summary>
public ReferenceSegment Reference { get; private set; } public ReferenceSegment? Reference { get; private set; }
/// <summary> /// <summary>
/// Returns the position in TextView the mouse cursor is currently hovering above. /// Returns the position in TextView the mouse cursor is currently hovering above.
@ -88,9 +88,9 @@ namespace ICSharpCode.ILSpy
public Point MousePosition { get; private set; } public Point MousePosition { get; private set; }
public static TextViewContext Create(SharpTreeView treeView = null, DecompilerTextView textView = null, ListBox listBox = null, DataGrid dataGrid = null) public static TextViewContext Create(SharpTreeView? treeView = null, DecompilerTextView? textView = null, ListBox? listBox = null, DataGrid? dataGrid = null)
{ {
ReferenceSegment reference; ReferenceSegment? reference;
if (textView != null) if (textView != null)
reference = textView.GetReferenceSegmentAtMousePosition(); reference = textView.GetReferenceSegmentAtMousePosition();
else if (listBox?.SelectedItem is SearchResult result) else if (listBox?.SelectedItem is SearchResult result)
@ -115,7 +115,7 @@ namespace ICSharpCode.ILSpy
TextView = textView, TextView = textView,
Reference = reference, Reference = reference,
Position = position, Position = position,
MousePosition = ((Visual)textView ?? treeView ?? (Visual)listBox ?? dataGrid).PointToScreen(Mouse.GetPosition((IInputElement)textView ?? treeView ?? (IInputElement)listBox ?? dataGrid)) MousePosition = ((Visual?)textView ?? treeView ?? (Visual?)listBox ?? dataGrid).PointToScreen(Mouse.GetPosition((IInputElement?)textView ?? treeView ?? (IInputElement?)listBox ?? dataGrid))
}; };
} }
} }
@ -291,7 +291,7 @@ namespace ICSharpCode.ILSpy
{ {
menu = new ContextMenu(); menu = new ContextMenu();
var menuGroups = new Dictionary<string, IExport<IContextMenuEntry, IContextMenuEntryMetadata>[]>(); var menuGroups = new Dictionary<string, IExport<IContextMenuEntry, IContextMenuEntryMetadata>[]>();
IExport<IContextMenuEntry, IContextMenuEntryMetadata>[] topLevelGroup = null; IExport<IContextMenuEntry, IContextMenuEntryMetadata>[]? topLevelGroup = null;
foreach (var group in entries.OrderBy(c => c.Metadata.Order).GroupBy(c => c.Metadata.ParentMenuID)) foreach (var group in entries.OrderBy(c => c.Metadata.Order).GroupBy(c => c.Metadata.ParentMenuID))
{ {
if (group.Key == null) if (group.Key == null)
@ -313,7 +313,7 @@ namespace ICSharpCode.ILSpy
bool needSeparatorForCategory = parent.Count > 0; bool needSeparatorForCategory = parent.Count > 0;
foreach (var entryPair in category) foreach (var entryPair in category)
{ {
IContextMenuEntry entry = entryPair.Value; IContextMenuEntry? entry = entryPair.Value;
if (entry.IsVisible(context)) if (entry.IsVisible(context))
{ {
if (needSeparatorForCategory) if (needSeparatorForCategory)

10
ILSpy/Controls/GridViewColumnAutoSize.cs

@ -52,25 +52,25 @@ namespace ICSharpCode.ILSpy.Controls
static void AutoWidthPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) static void AutoWidthPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{ {
ListView grid = sender as ListView; ListView? grid = sender as ListView;
if (grid == null) if (grid == null)
return; return;
grid.SizeChanged += delegate (object listView, SizeChangedEventArgs e) { grid.SizeChanged += delegate (object listView, SizeChangedEventArgs e) {
ListView lv = listView as ListView; ListView? lv = listView as ListView;
if (lv == null) if (lv == null)
return; return;
GridView v = lv.View as GridView; GridView? v = lv.View as GridView;
if (v == null) if (v == null)
return; return;
CalculateSizes(v, GetAutoWidth(lv), e.NewSize.Width); CalculateSizes(v, GetAutoWidth(lv), e.NewSize.Width);
}; };
GridView view = grid.View as GridView; GridView? view = grid.View as GridView;
if (view == null) if (view == null)
return; return;
CalculateSizes(view, args.NewValue as string, grid.ActualWidth); CalculateSizes(view, args.NewValue as string, grid.ActualWidth);
} }
static void CalculateSizes(GridView view, string sizeValue, double fullWidth) static void CalculateSizes(GridView view, string? sizeValue, double fullWidth)
{ {
string[] sizes = (sizeValue ?? "").Split(';'); string[] sizes = (sizeValue ?? "").Split(';');

2
ILSpy/Controls/SearchBox.cs

@ -137,7 +137,7 @@ namespace ICSharpCode.ILSpy.Controls
{ {
base.OnApplyTemplate(); base.OnApplyTemplate();
Border iconBorder = GetTemplateChild("PART_IconBorder") as Border; Border? iconBorder = GetTemplateChild("PART_IconBorder") as Border;
if (iconBorder != null) if (iconBorder != null)
{ {
iconBorder.MouseLeftButtonUp += IconBorder_MouseLeftButtonUp; iconBorder.MouseLeftButtonUp += IconBorder_MouseLeftButtonUp;

12
ILSpy/Controls/SortableGridViewColumn.cs

@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy.Controls
static void OnSortDirectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) static void OnSortDirectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{ {
ListView grid = sender as ListView; ListView? grid = sender as ListView;
if (grid != null) if (grid != null)
{ {
SortableGridViewColumn col = GetCurrentSortColumn(grid); SortableGridViewColumn col = GetCurrentSortColumn(grid);
@ -101,7 +101,7 @@ namespace ICSharpCode.ILSpy.Controls
static void OnCurrentSortColumnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) static void OnCurrentSortColumnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{ {
ListView grid = sender as ListView; ListView? grid = sender as ListView;
if (grid != null) if (grid != null)
{ {
SortableGridViewColumn oldColumn = (SortableGridViewColumn)args.OldValue; SortableGridViewColumn oldColumn = (SortableGridViewColumn)args.OldValue;
@ -134,7 +134,7 @@ namespace ICSharpCode.ILSpy.Controls
static void OnSortModeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) static void OnSortModeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{ {
ListView grid = sender as ListView; ListView? grid = sender as ListView;
if (grid != null) if (grid != null)
{ {
if ((ListViewSortMode)args.NewValue != ListViewSortMode.None) if ((ListViewSortMode)args.NewValue != ListViewSortMode.None)
@ -146,8 +146,8 @@ namespace ICSharpCode.ILSpy.Controls
static void GridViewColumnHeaderClickHandler(object sender, RoutedEventArgs e) static void GridViewColumnHeaderClickHandler(object sender, RoutedEventArgs e)
{ {
ListView grid = sender as ListView; ListView? grid = sender as ListView;
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader; GridViewColumnHeader? headerClicked = e.OriginalSource as GridViewColumnHeader;
if (grid != null && headerClicked != null && headerClicked.Role != GridViewColumnHeaderRole.Padding) if (grid != null && headerClicked != null && headerClicked.Role != GridViewColumnHeaderRole.Padding)
{ {
if (headerClicked.Column == GetCurrentSortColumn(grid)) if (headerClicked.Column == GetCurrentSortColumn(grid))
@ -188,7 +188,7 @@ namespace ICSharpCode.ILSpy.Controls
string sortBy = column.SortBy; string sortBy = column.SortBy;
if (sortBy == null) if (sortBy == null)
{ {
Binding binding = column.DisplayMemberBinding as Binding; Binding? binding = column.DisplayMemberBinding as Binding;
if (binding != null && binding.Path != null) if (binding != null && binding.Path != null)
{ {
sortBy = binding.Path.Path; sortBy = binding.Path.Path;

20
ILSpy/Controls/TreeView/SharpTreeView.cs

@ -176,8 +176,8 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
// Deselect nodes that are being hidden, if any remain in the tree // Deselect nodes that are being hidden, if any remain in the tree
if (e.Action == NotifyCollectionChangedAction.Remove && Items.Count > 0) if (e.Action == NotifyCollectionChangedAction.Remove && Items.Count > 0)
{ {
List<SharpTreeNode> selectedOldItems = null; List<SharpTreeNode>? selectedOldItems = null;
foreach (SharpTreeNode node in e.OldItems) foreach (SharpTreeNode node in e.OldItems!)
{ {
if (node.IsSelected) if (node.IsSelected)
{ {
@ -194,7 +194,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
} }
} }
void UpdateFocusedNode(List<SharpTreeNode> newSelection, int topSelectedIndex) void UpdateFocusedNode(List<SharpTreeNode>? newSelection, int topSelectedIndex)
{ {
if (updatesLocked) if (updatesLocked)
return; return;
@ -222,7 +222,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
protected override void PrepareContainerForItemOverride(DependencyObject element, object item) protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{ {
base.PrepareContainerForItemOverride(element, item); base.PrepareContainerForItemOverride(element, item);
SharpTreeViewItem container = element as SharpTreeViewItem; SharpTreeViewItem? container = element as SharpTreeViewItem;
container.ParentTreeView = this; container.ParentTreeView = this;
// Make sure that the line renderer takes into account the new bound data // Make sure that the line renderer takes into account the new bound data
if (container.NodeView != null) if (container.NodeView != null)
@ -244,7 +244,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
SharpTreeNode lastVisibleChild = node; SharpTreeNode lastVisibleChild = node;
while (true) while (true)
{ {
SharpTreeNode tmp = lastVisibleChild.Children.LastOrDefault(c => c.IsVisible); SharpTreeNode? tmp = lastVisibleChild.Children.LastOrDefault(c => c.IsVisible);
if (tmp != null) if (tmp != null)
{ {
lastVisibleChild = tmp; lastVisibleChild = tmp;
@ -269,7 +269,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
protected override void OnKeyDown(KeyEventArgs e) protected override void OnKeyDown(KeyEventArgs e)
{ {
SharpTreeViewItem container = e.OriginalSource as SharpTreeViewItem; SharpTreeViewItem? container = e.OriginalSource as SharpTreeViewItem;
switch (e.Key) switch (e.Key)
{ {
case Key.Left: case Key.Left:
@ -422,7 +422,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
object? OnFocusItem(object item) object? OnFocusItem(object item)
{ {
FrameworkElement element = this.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement; FrameworkElement? element = this.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
if (element != null) if (element != null)
{ {
element.Focus(); element.Focus();
@ -606,7 +606,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
void TryAddDropTarget(List<DropTarget> targets, SharpTreeViewItem item, DropPlace place, DragEventArgs e) void TryAddDropTarget(List<DropTarget> targets, SharpTreeViewItem item, DropPlace place, DragEventArgs e)
{ {
SharpTreeNode node; SharpTreeNode? node;
int index; int index;
GetNodeAndIndex(item, place, out node, out index); GetNodeAndIndex(item, place, out node, out index);
@ -627,7 +627,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
} }
} }
void GetNodeAndIndex(SharpTreeViewItem item, DropPlace place, out SharpTreeNode node, out int index) void GetNodeAndIndex(SharpTreeViewItem item, DropPlace place, out SharpTreeNode? node, out int index)
{ {
node = null; node = null;
index = 0; index = 0;
@ -697,7 +697,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
insertMarker.Margin = new Thickness(p.X, p.Y, 0, 0); insertMarker.Margin = new Thickness(p.X, p.Y, 0, 0);
SharpTreeNodeView secondNodeView = null; SharpTreeNodeView? secondNodeView = null;
var index = flattener.IndexOf(item.Node); var index = flattener.IndexOf(item.Node);
if (place == DropPlace.Before) if (place == DropPlace.Before)

2
ILSpy/Controls/TreeView/SharpTreeViewTextSearch.cs

@ -116,7 +116,7 @@ namespace ICSharpCode.ILSpy.Controls.TreeView
var item = (SharpTreeNode)treeView.Items[i]; var item = (SharpTreeNode)treeView.Items[i];
if (item != null && item.Text != null) if (item != null && item.Text != null)
{ {
string text = item.Text.ToString(); string text = item.Text.ToString() ?? "";
if (text.StartsWith(needle, comparisonType)) if (text.StartsWith(needle, comparisonType))
{ {
charWasUsed = true; charWasUsed = true;

4
ILSpy/Controls/ZoomScrollViewer.cs

@ -103,7 +103,7 @@ namespace ICSharpCode.ILSpy.Controls
static void CalculateZoomButtonCollapsed(DependencyObject d, DependencyPropertyChangedEventArgs e) static void CalculateZoomButtonCollapsed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{ {
ZoomScrollViewer z = d as ZoomScrollViewer; ZoomScrollViewer? z = d as ZoomScrollViewer;
if (z != null) if (z != null)
z.ComputedZoomButtonCollapsed = (z.AlwaysShowZoomButtons == false) && (z.CurrentZoom == 1.0); z.ComputedZoomButtonCollapsed = (z.AlwaysShowZoomButtons == false) && (z.CurrentZoom == 1.0);
} }
@ -117,7 +117,7 @@ namespace ICSharpCode.ILSpy.Controls
newZoom = Math.Max(this.MinimumZoom, Math.Min(this.MaximumZoom, newZoom)); newZoom = Math.Max(this.MinimumZoom, Math.Min(this.MaximumZoom, newZoom));
// adjust scroll position so that mouse stays over the same virtual coordinate // adjust scroll position so that mouse stays over the same virtual coordinate
ContentPresenter presenter = Template.FindName("PART_Presenter", this) as ContentPresenter; ContentPresenter? presenter = Template.FindName("PART_Presenter", this) as ContentPresenter;
Vector relMousePos; Vector relMousePos;
if (presenter != null) if (presenter != null)
{ {

4
ILSpy/Docking/DockWorkspace.cs

@ -84,7 +84,7 @@ namespace ICSharpCode.ILSpy.Docking
private void Documents_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) private void Documents_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{ {
var collection = (PaneCollection<TabPageModel>)sender; var collection = (PaneCollection<TabPageModel>?)sender;
if (e.Action == NotifyCollectionChangedAction.Add) if (e.Action == NotifyCollectionChangedAction.Add)
{ {
ActiveTabPage = e.NewItems?[0] as TabPageModel; ActiveTabPage = e.NewItems?[0] as TabPageModel;
@ -246,7 +246,7 @@ namespace ICSharpCode.ILSpy.Docking
{ {
var anchorable = layout.Descendents().OfType<LayoutAnchorable>().FirstOrDefault(x => x.Content is T) var anchorable = layout.Descendents().OfType<LayoutAnchorable>().FirstOrDefault(x => x.Content is T)
?? layout.Hidden.First(x => x.Content is T); ?? layout.Hidden.First(x => x.Content is T);
return (LayoutAnchorablePane)previousContainerProperty.GetValue(anchorable) ?? (LayoutAnchorablePane)anchorable.Parent; return (LayoutAnchorablePane?)previousContainerProperty.GetValue(anchorable) ?? (LayoutAnchorablePane)anchorable.Parent;
} }
} }

2
ILSpy/ISmartTextOutput.cs

@ -52,7 +52,7 @@ namespace ICSharpCode.ILSpy
/// <summary> /// <summary>
/// Creates a button. /// Creates a button.
/// </summary> /// </summary>
public static void AddButton(this ISmartTextOutput output, ImageSource icon, string text, RoutedEventHandler click) public static void AddButton(this ISmartTextOutput output, ImageSource? icon, string text, RoutedEventHandler click)
{ {
output.AddUIElement( output.AddUIElement(
delegate { delegate {

16
ILSpy/Images/Images.cs

@ -150,12 +150,12 @@ namespace ICSharpCode.ILSpy
return image; return image;
} }
public static Drawing LoadDrawingGroup(object part, string icon) public static Drawing LoadDrawingGroup(object? part, string icon)
{ {
return (Drawing)Application.LoadComponent(GetUri(part, icon + ".xaml", absolute: false)); return (Drawing)Application.LoadComponent(GetUri(part, icon + ".xaml", absolute: false));
} }
private static Uri GetUri(object part, string icon, bool absolute = true) private static Uri GetUri(object? part, string icon, bool absolute = true)
{ {
Uri uri; Uri uri;
var assembly = part?.GetType().Assembly; var assembly = part?.GetType().Assembly;
@ -212,15 +212,15 @@ namespace ICSharpCode.ILSpy
return memberIconCache.GetIcon(icon, overlay, isStatic); return memberIconCache.GetIcon(icon, overlay, isStatic);
} }
private static ImageSource GetIcon(string baseImage, string overlay = null, bool isStatic = false) private static ImageSource GetIcon(string baseImage, string? overlay = null, bool isStatic = false)
{ {
ImageSource baseImageSource = Load(baseImage); ImageSource baseImageSource = Load(baseImage);
ImageSource overlayImageSource = overlay != null ? Load(overlay) : null; ImageSource? overlayImageSource = overlay != null ? Load(overlay) : null;
return CreateOverlayImage(baseImageSource, overlayImageSource, isStatic); return CreateOverlayImage(baseImageSource, overlayImageSource, isStatic);
} }
private static ImageSource CreateOverlayImage(ImageSource baseImage, ImageSource overlay, bool isStatic) private static ImageSource CreateOverlayImage(ImageSource baseImage, ImageSource? overlay, bool isStatic)
{ {
var group = new DrawingGroup(); var group = new DrawingGroup();
@ -391,16 +391,16 @@ namespace ICSharpCode.ILSpy
private ImageSource BuildMemberIcon(T icon, AccessOverlayIcon overlay, bool isStatic) private ImageSource BuildMemberIcon(T icon, AccessOverlayIcon overlay, bool isStatic)
{ {
ImageSource baseImage = GetBaseImage(icon); ImageSource baseImage = GetBaseImage(icon);
ImageSource overlayImage = GetOverlayImage(overlay); ImageSource? overlayImage = GetOverlayImage(overlay);
return CreateOverlayImage(baseImage, overlayImage, isStatic); return CreateOverlayImage(baseImage, overlayImage, isStatic);
} }
protected abstract ImageSource GetBaseImage(T icon); protected abstract ImageSource GetBaseImage(T icon);
private static ImageSource GetOverlayImage(AccessOverlayIcon overlay) private static ImageSource? GetOverlayImage(AccessOverlayIcon overlay)
{ {
ImageSource overlayImage; ImageSource? overlayImage;
switch (overlay) switch (overlay)
{ {
case AccessOverlayIcon.Public: case AccessOverlayIcon.Public:

8
ILSpy/Languages/CSharpHighlightingTokenWriter.cs

@ -122,7 +122,7 @@ namespace ICSharpCode.ILSpy
public override void WriteKeyword(Role role, string keyword) public override void WriteKeyword(Role role, string keyword)
{ {
HighlightingColor color = null; HighlightingColor? color = null;
switch (keyword) switch (keyword)
{ {
case "namespace": case "namespace":
@ -299,7 +299,7 @@ namespace ICSharpCode.ILSpy
public override void WritePrimitiveType(string type) public override void WritePrimitiveType(string type)
{ {
HighlightingColor color = null; HighlightingColor? color = null;
switch (type) switch (type)
{ {
case "new": case "new":
@ -348,7 +348,7 @@ namespace ICSharpCode.ILSpy
public override void WriteIdentifier(Identifier identifier) public override void WriteIdentifier(Identifier identifier)
{ {
HighlightingColor color = null; HighlightingColor? color = null;
if (identifier.Parent?.GetResolveResult() is ILVariableResolveResult rr) if (identifier.Parent?.GetResolveResult() is ILVariableResolveResult rr)
{ {
if (rr.Variable.Kind == VariableKind.Parameter) if (rr.Variable.Kind == VariableKind.Parameter)
@ -454,7 +454,7 @@ namespace ICSharpCode.ILSpy
public override void WritePrimitiveValue(object value, Decompiler.CSharp.Syntax.LiteralFormat format) public override void WritePrimitiveValue(object value, Decompiler.CSharp.Syntax.LiteralFormat format)
{ {
HighlightingColor color = null; HighlightingColor? color = null;
if (value is null) if (value is null)
{ {
color = valueKeywordColor; color = valueKeywordColor;

18
ILSpy/Languages/CSharpLanguage.cs

@ -95,7 +95,7 @@ namespace ICSharpCode.ILSpy
get { return ".csproj"; } get { return ".csproj"; }
} }
IReadOnlyList<LanguageVersion> versions; IReadOnlyList<LanguageVersion>? versions;
public override IReadOnlyList<LanguageVersion> LanguageVersions { public override IReadOnlyList<LanguageVersion> LanguageVersions {
get { get {
@ -151,7 +151,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
{ {
MetadataFile assembly = method.ParentModule.MetadataFile; MetadataFile? assembly = method.ParentModule.MetadataFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options); CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output);
@ -182,7 +182,7 @@ namespace ICSharpCode.ILSpy
public void Run(AstNode rootNode, TransformContext context) public void Run(AstNode rootNode, TransformContext context)
{ {
ConstructorDeclaration ctorDecl = null; ConstructorDeclaration? ctorDecl = null;
foreach (var node in rootNode.Children) foreach (var node in rootNode.Children)
{ {
switch (node) switch (node)
@ -247,7 +247,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options) public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options)
{ {
MetadataFile assembly = property.ParentModule.MetadataFile; MetadataFile? assembly = property.ParentModule.MetadataFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options); CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output);
@ -258,7 +258,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options) public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options)
{ {
MetadataFile assembly = field.ParentModule.MetadataFile; MetadataFile? assembly = field.ParentModule.MetadataFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options); CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output);
@ -348,7 +348,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options) public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options)
{ {
MetadataFile assembly = type.ParentModule.MetadataFile; MetadataFile? assembly = type.ParentModule.MetadataFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options); CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output);
@ -380,8 +380,8 @@ namespace ICSharpCode.ILSpy
AddWarningMessage(module, output, line1); AddWarningMessage(module, output, line1);
} }
void AddWarningMessage(MetadataFile module, ITextOutput output, string line1, string line2 = null, void AddWarningMessage(MetadataFile module, ITextOutput output, string line1, string? line2 = null,
string buttonText = null, System.Windows.Media.ImageSource buttonImage = null, RoutedEventHandler buttonClickHandler = null) string? buttonText = null, System.Windows.Media.ImageSource? buttonImage = null, RoutedEventHandler? buttonClickHandler = null)
{ {
if (output is ISmartTextOutput fancyOutput) if (output is ISmartTextOutput fancyOutput)
{ {
@ -775,7 +775,7 @@ namespace ICSharpCode.ILSpy
public override bool ShowMember(IEntity member) public override bool ShowMember(IEntity member)
{ {
MetadataFile assembly = member.ParentModule.MetadataFile; MetadataFile? assembly = member.ParentModule?.MetadataFile;
return showAllMembers || !CSharpDecompiler.MemberIsHidden(assembly, member.MetadataToken, SettingsService.Instance.DecompilerSettings); return showAllMembers || !CSharpDecompiler.MemberIsHidden(assembly, member.MetadataToken, SettingsService.Instance.DecompilerSettings);
} }

14
ILSpy/Languages/ILLanguage.cs

@ -73,7 +73,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
{ {
var dis = CreateDisassembler(output, options); var dis = CreateDisassembler(output, options);
MetadataFile module = method.ParentModule.MetadataFile; MetadataFile? module = method.ParentModule?.MetadataFile;
dis.AssemblyResolver = module.GetAssemblyResolver(); dis.AssemblyResolver = module.GetAssemblyResolver();
dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DebugInfo = module.GetDebugInfoOrNull();
dis.DisassembleMethod(module, (MethodDefinitionHandle)method.MetadataToken); dis.DisassembleMethod(module, (MethodDefinitionHandle)method.MetadataToken);
@ -82,7 +82,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options) public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options)
{ {
var dis = CreateDisassembler(output, options); var dis = CreateDisassembler(output, options);
MetadataFile module = field.ParentModule.MetadataFile; MetadataFile? module = field.ParentModule?.MetadataFile;
dis.AssemblyResolver = module.GetAssemblyResolver(); dis.AssemblyResolver = module.GetAssemblyResolver();
dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DebugInfo = module.GetDebugInfoOrNull();
dis.DisassembleField(module, (FieldDefinitionHandle)field.MetadataToken); dis.DisassembleField(module, (FieldDefinitionHandle)field.MetadataToken);
@ -91,7 +91,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options) public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options)
{ {
var dis = CreateDisassembler(output, options); var dis = CreateDisassembler(output, options);
MetadataFile module = property.ParentModule.MetadataFile; MetadataFile? module = property.ParentModule?.MetadataFile;
dis.AssemblyResolver = module.GetAssemblyResolver(); dis.AssemblyResolver = module.GetAssemblyResolver();
dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DebugInfo = module.GetDebugInfoOrNull();
dis.DisassembleProperty(module, (PropertyDefinitionHandle)property.MetadataToken); dis.DisassembleProperty(module, (PropertyDefinitionHandle)property.MetadataToken);
@ -117,7 +117,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileEvent(IEvent ev, ITextOutput output, DecompilationOptions options) public override void DecompileEvent(IEvent ev, ITextOutput output, DecompilationOptions options)
{ {
var dis = CreateDisassembler(output, options); var dis = CreateDisassembler(output, options);
MetadataFile module = ev.ParentModule.MetadataFile; MetadataFile? module = ev.ParentModule?.MetadataFile;
dis.AssemblyResolver = module.GetAssemblyResolver(); dis.AssemblyResolver = module.GetAssemblyResolver();
dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DebugInfo = module.GetDebugInfoOrNull();
dis.DisassembleEvent(module, (EventDefinitionHandle)ev.MetadataToken); dis.DisassembleEvent(module, (EventDefinitionHandle)ev.MetadataToken);
@ -148,7 +148,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options) public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options)
{ {
var dis = CreateDisassembler(output, options); var dis = CreateDisassembler(output, options);
MetadataFile module = type.ParentModule.MetadataFile; MetadataFile? module = type.ParentModule?.MetadataFile;
dis.AssemblyResolver = module.GetAssemblyResolver(); dis.AssemblyResolver = module.GetAssemblyResolver();
dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DebugInfo = module.GetDebugInfoOrNull();
dis.DisassembleType(module, (TypeDefinitionHandle)type.MetadataToken); dis.DisassembleType(module, (TypeDefinitionHandle)type.MetadataToken);
@ -157,7 +157,7 @@ namespace ICSharpCode.ILSpy
public override void DecompileNamespace(string nameSpace, IEnumerable<ITypeDefinition> types, ITextOutput output, DecompilationOptions options) public override void DecompileNamespace(string nameSpace, IEnumerable<ITypeDefinition> types, ITextOutput output, DecompilationOptions options)
{ {
var dis = CreateDisassembler(output, options); var dis = CreateDisassembler(output, options);
MetadataFile module = types.FirstOrDefault()?.ParentModule.MetadataFile; MetadataFile? module = types.FirstOrDefault()?.ParentModule?.MetadataFile;
dis.AssemblyResolver = module.GetAssemblyResolver(); dis.AssemblyResolver = module.GetAssemblyResolver();
dis.DebugInfo = module.GetDebugInfoOrNull(); dis.DebugInfo = module.GetDebugInfoOrNull();
dis.DisassembleNamespace(nameSpace, module, types.Select(t => (TypeDefinitionHandle)t.MetadataToken)); dis.DisassembleNamespace(nameSpace, module, types.Select(t => (TypeDefinitionHandle)t.MetadataToken));
@ -199,7 +199,7 @@ namespace ICSharpCode.ILSpy
{ {
var output = new AvalonEditTextOutput() { IgnoreNewLineAndIndent = true }; var output = new AvalonEditTextOutput() { IgnoreNewLineAndIndent = true };
var disasm = CreateDisassembler(output, MainWindow.Instance.CreateDecompilationOptions()); var disasm = CreateDisassembler(output, MainWindow.Instance.CreateDecompilationOptions());
MetadataFile module = entity.ParentModule?.MetadataFile; MetadataFile? module = entity.ParentModule?.MetadataFile;
if (module == null) if (module == null)
{ {
return null; return null;

2
ILSpy/Languages/Language.cs

@ -125,7 +125,7 @@ namespace ICSharpCode.ILSpy
{ {
WriteCommentLine(output, metadata.GetString(name.Name) + " [WinRT]"); WriteCommentLine(output, metadata.GetString(name.Name) + " [WinRT]");
} }
else if (metadata.TryGetFullAssemblyName(out string assemblyName)) else if (metadata.TryGetFullAssemblyName(out string? assemblyName))
{ {
WriteCommentLine(output, assemblyName); WriteCommentLine(output, assemblyName);
} }

40
ILSpy/MainWindow.xaml.cs

@ -318,7 +318,7 @@ namespace ICSharpCode.ILSpy
{ {
return null; return null;
} }
string value = Properties.Resources.ResourceManager.GetString(key); string? value = Properties.Resources.ResourceManager.GetString(key);
if (!string.IsNullOrEmpty(value)) if (!string.IsNullOrEmpty(value))
{ {
return value; return value;
@ -659,13 +659,13 @@ namespace ICSharpCode.ILSpy
string namespaceName = navigateTo.Substring(2); string namespaceName = navigateTo.Substring(2);
foreach (LoadedAssembly asm in relevantAssemblies) foreach (LoadedAssembly asm in relevantAssemblies)
{ {
AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm); AssemblyTreeNode? asmNode = assemblyListTreeNode.FindAssemblyNode(asm);
if (asmNode != null) if (asmNode != null)
{ {
// FindNamespaceNode() blocks the UI if the assembly is not yet loaded, // FindNamespaceNode() blocks the UI if the assembly is not yet loaded,
// so use an async wait instead. // so use an async wait instead.
await asm.GetMetadataFileAsync().Catch<Exception>(ex => { }); await asm.GetMetadataFileAsync().Catch<Exception>(ex => { });
NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName); NamespaceTreeNode? nsNode = asmNode.FindNamespaceNode(namespaceName);
if (nsNode != null) if (nsNode != null)
{ {
found = true; found = true;
@ -686,7 +686,7 @@ namespace ICSharpCode.ILSpy
} }
else else
{ {
IEntity mr = await Task.Run(() => FindEntityInRelevantAssemblies(navigateTo, relevantAssemblies)); IEntity? mr = await Task.Run(() => FindEntityInRelevantAssemblies(navigateTo, relevantAssemblies));
// Make sure we wait for assemblies being loaded... // Make sure we wait for assemblies being loaded...
// BeginInvoke in LoadedAssembly.LookupReferencedAssemblyInternal // BeginInvoke in LoadedAssembly.LookupReferencedAssemblyInternal
await Dispatcher.InvokeAsync(delegate { }, DispatcherPriority.Normal); await Dispatcher.InvokeAsync(delegate { }, DispatcherPriority.Normal);
@ -710,7 +710,7 @@ namespace ICSharpCode.ILSpy
{ {
// NavigateTo == null and an assembly was given on the command-line: // NavigateTo == null and an assembly was given on the command-line:
// Select the newly loaded assembly // Select the newly loaded assembly
AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(relevantAssemblies[0]); AssemblyTreeNode? asmNode = assemblyListTreeNode.FindAssemblyNode(relevantAssemblies[0]);
if (asmNode != null && AssemblyTreeView.SelectedItem == initialSelection) if (asmNode != null && AssemblyTreeView.SelectedItem == initialSelection)
{ {
SelectNode(asmNode); SelectNode(asmNode);
@ -718,7 +718,7 @@ namespace ICSharpCode.ILSpy
} }
else if (spySettings != null) else if (spySettings != null)
{ {
SharpTreeNode node = null; SharpTreeNode? node = null;
if (activeTreeViewPath?.Length > 0) if (activeTreeViewPath?.Length > 0)
{ {
foreach (var asm in CurrentAssemblyList.GetAssemblies()) foreach (var asm in CurrentAssemblyList.GetAssemblies())
@ -772,7 +772,7 @@ namespace ICSharpCode.ILSpy
: new SimpleCompilation((PEFile)module, MinimalCorlib.Instance); : new SimpleCompilation((PEFile)module, MinimalCorlib.Instance);
return memberRef == null return memberRef == null
? typeRef.Resolve(new SimpleTypeResolveContext(compilation)) as ITypeDefinition ? typeRef.Resolve(new SimpleTypeResolveContext(compilation)) as ITypeDefinition
: (IEntity)memberRef.Resolve(new SimpleTypeResolveContext(compilation)); : (IEntity?)memberRef.Resolve(new SimpleTypeResolveContext(compilation));
} }
} }
return null; return null;
@ -875,7 +875,7 @@ namespace ICSharpCode.ILSpy
public async Task ShowMessageIfUpdatesAvailableAsync(ILSpySettings spySettings, bool forceCheck = false) public async Task ShowMessageIfUpdatesAvailableAsync(ILSpySettings spySettings, bool forceCheck = false)
{ {
string downloadUrl; string? downloadUrl;
if (forceCheck) if (forceCheck)
{ {
downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(spySettings); downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(spySettings);
@ -903,12 +903,12 @@ namespace ICSharpCode.ILSpy
else else
{ {
updatePanel.Visibility = Visibility.Collapsed; updatePanel.Visibility = Visibility.Collapsed;
string downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(ILSpySettings.Load()); string? downloadUrl = await NotifyOfUpdatesStrategy.CheckForUpdatesAsync(ILSpySettings.Load());
AdjustUpdateUIAfterCheck(downloadUrl, true); AdjustUpdateUIAfterCheck(downloadUrl, true);
} }
} }
void AdjustUpdateUIAfterCheck(string downloadUrl, bool displayMessage) void AdjustUpdateUIAfterCheck(string? downloadUrl, bool displayMessage)
{ {
updateAvailableDownloadUrl = downloadUrl; updateAvailableDownloadUrl = downloadUrl;
updatePanel.Visibility = displayMessage ? Visibility.Visible : Visibility.Collapsed; updatePanel.Visibility = displayMessage ? Visibility.Visible : Visibility.Collapsed;
@ -1113,8 +1113,8 @@ namespace ICSharpCode.ILSpy
{ {
if (path == null) if (path == null)
return null; return null;
SharpTreeNode node = AssemblyTreeView.Root; SharpTreeNode? node = AssemblyTreeView.Root;
SharpTreeNode bestMatch = node; SharpTreeNode? bestMatch = node;
foreach (var element in path) foreach (var element in path)
{ {
if (node == null) if (node == null)
@ -1237,7 +1237,7 @@ namespace ICSharpCode.ILSpy
} }
break; break;
default: default:
ILSpyTreeNode treeNode = FindTreeNode(reference); ILSpyTreeNode? treeNode = FindTreeNode(reference);
if (treeNode != null) if (treeNode != null)
SelectNode(treeNode, inNewTabPage); SelectNode(treeNode, inNewTabPage);
break; break;
@ -1301,9 +1301,9 @@ namespace ICSharpCode.ILSpy
LoadAssemblies(fileNames, focusNode: focusNode); LoadAssemblies(fileNames, focusNode: focusNode);
} }
void LoadAssemblies(IEnumerable<string> fileNames, List<LoadedAssembly> loadedAssemblies = null, bool focusNode = true) void LoadAssemblies(IEnumerable<string> fileNames, List<LoadedAssembly>? loadedAssemblies = null, bool focusNode = true)
{ {
SharpTreeNode lastNode = null; SharpTreeNode? lastNode = null;
foreach (string file in fileNames) foreach (string file in fileNames)
{ {
var asm = assemblyList.OpenAssembly(file); var asm = assemblyList.OpenAssembly(file);
@ -1367,7 +1367,7 @@ namespace ICSharpCode.ILSpy
void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e) void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ {
DecompilerTextViewState state = null; DecompilerTextViewState? state = null;
if (refreshInProgress || changingActiveTab) if (refreshInProgress || changingActiveTab)
{ {
state = DockWorkspace.Instance.ActiveTabPage.GetState() as DecompilerTextViewState; state = DockWorkspace.Instance.ActiveTabPage.GetState() as DecompilerTextViewState;
@ -1385,7 +1385,7 @@ namespace ICSharpCode.ILSpy
Task decompilationTask; Task decompilationTask;
bool ignoreDecompilationRequests; bool ignoreDecompilationRequests;
void DecompileSelectedNodes(DecompilerTextViewState newState = null, bool recordHistory = true) void DecompileSelectedNodes(DecompilerTextViewState? newState = null, bool recordHistory = true)
{ {
if (ignoreDecompilationRequests) if (ignoreDecompilationRequests)
return; return;
@ -1406,7 +1406,7 @@ namespace ICSharpCode.ILSpy
if (AssemblyTreeView.SelectedItems.Count == 1) if (AssemblyTreeView.SelectedItems.Count == 1)
{ {
ILSpyTreeNode node = AssemblyTreeView.SelectedItem as ILSpyTreeNode; ILSpyTreeNode? node = AssemblyTreeView.SelectedItem as ILSpyTreeNode;
if (node != null && node.View(DockWorkspace.Instance.ActiveTabPage)) if (node != null && node.View(DockWorkspace.Instance.ActiveTabPage))
return; return;
} }
@ -1533,11 +1533,11 @@ namespace ICSharpCode.ILSpy
Title = e.Uri.AbsolutePath, Title = e.Uri.AbsolutePath,
EnableHyperlinks = true EnableHyperlinks = true
}; };
using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath)) using (Stream? s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath))
{ {
using (StreamReader r = new StreamReader(s)) using (StreamReader r = new StreamReader(s))
{ {
string line; string? line;
while ((line = r.ReadLine()) != null) while ((line = r.ReadLine()) != null)
{ {
output.Write(line); output.Write(line);

2
ILSpy/Metadata/CorTables/EventTableTreeNode.cs

@ -92,7 +92,7 @@ namespace ICSharpCode.ILSpy.Metadata
public string Name => metadataFile.Metadata.GetString(eventDef.Name); public string Name => metadataFile.Metadata.GetString(eventDef.Name);
IEntity IMemberTreeNode.Member { IEntity? IMemberTreeNode.Member {
get { get {
return ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); return ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle);
} }

2
ILSpy/Metadata/CorTables/FieldTableTreeNode.cs

@ -95,7 +95,7 @@ namespace ICSharpCode.ILSpy.Metadata
public string NameTooltip => $"{MetadataTokens.GetHeapOffset(fieldDef.Name):X} \"{Name}\""; public string NameTooltip => $"{MetadataTokens.GetHeapOffset(fieldDef.Name):X} \"{Name}\"";
IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle);
[ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)]
public int Signature => MetadataTokens.GetHeapOffset(fieldDef.Signature); public int Signature => MetadataTokens.GetHeapOffset(fieldDef.Signature);

2
ILSpy/Metadata/CorTables/MethodTableTreeNode.cs

@ -131,7 +131,7 @@ namespace ICSharpCode.ILSpy.Metadata
} }
} }
IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle); IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule)?.GetDefinition(handle);
public MethodDefEntry(MetadataFile metadataFile, MethodDefinitionHandle handle) public MethodDefEntry(MetadataFile metadataFile, MethodDefinitionHandle handle)
{ {

2
ILSpy/Metadata/CorTables/PropertyTableTreeNode.cs

@ -92,7 +92,7 @@ namespace ICSharpCode.ILSpy.Metadata
public string NameTooltip => $"{MetadataTokens.GetHeapOffset(propertyDef.Name):X} \"{Name}\""; public string NameTooltip => $"{MetadataTokens.GetHeapOffset(propertyDef.Name):X} \"{Name}\"";
IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle); IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle);
[ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)]
public int Signature => MetadataTokens.GetHeapOffset(propertyDef.Signature); public int Signature => MetadataTokens.GetHeapOffset(propertyDef.Signature);

2
ILSpy/Metadata/CorTables/TypeDefTableTreeNode.cs

@ -173,7 +173,7 @@ namespace ICSharpCode.ILSpy.Metadata
} }
} }
IEntity IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle); IEntity? IMemberTreeNode.Member => ((MetadataModule)metadataFile.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle);
public TypeDefEntry(MetadataFile metadataFile, TypeDefinitionHandle handle) public TypeDefEntry(MetadataFile metadataFile, TypeDefinitionHandle handle)
{ {

2
ILSpy/Metadata/DebugTables/CustomDebugInformationTableTreeNode.cs

@ -47,7 +47,7 @@ namespace ICSharpCode.ILSpy.Metadata
view.RowDetailsTemplateSelector = new CustomDebugInformationDetailsTemplateSelector(); view.RowDetailsTemplateSelector = new CustomDebugInformationDetailsTemplateSelector();
var list = new List<CustomDebugInformationEntry>(); var list = new List<CustomDebugInformationEntry>();
CustomDebugInformationEntry scrollTargetEntry = default; CustomDebugInformationEntry? scrollTargetEntry = default;
foreach (var row in metadataFile.Metadata.CustomDebugInformation) foreach (var row in metadataFile.Metadata.CustomDebugInformation)
{ {

4
ILSpy/Metadata/GoToTokenCommand.cs

@ -51,7 +51,7 @@ namespace ICSharpCode.ILSpy.Commands
return context.DataGrid?.Name == "MetadataView" && GetSelectedToken(context.DataGrid, out _) != null; return context.DataGrid?.Name == "MetadataView" && GetSelectedToken(context.DataGrid, out _) != null;
} }
private int? GetSelectedToken(DataGrid grid, out MetadataFile module) private int? GetSelectedToken(DataGrid grid, out MetadataFile? module)
{ {
module = null; module = null;
if (grid == null) if (grid == null)
@ -75,7 +75,7 @@ namespace ICSharpCode.ILSpy.Commands
{ {
public void Execute(TextViewContext context) public void Execute(TextViewContext context)
{ {
string content = GetSelectedCellContent(context.DataGrid, context.MousePosition); string? content = GetSelectedCellContent(context.DataGrid, context.MousePosition);
Clipboard.SetText(content); Clipboard.SetText(content);
} }

2
ILSpy/NavigationState.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.ILSpy
public NavigationState(TabPageModel tabPage, ViewState viewState) public NavigationState(TabPageModel tabPage, ViewState viewState)
{ {
this.TabPage = tabPage; this.TabPage = tabPage;
this.treeNodes = new HashSet<SharpTreeNode>((IEnumerable<SharpTreeNode>)viewState.DecompiledNodes ?? Array.Empty<SharpTreeNode>()); this.treeNodes = new HashSet<SharpTreeNode>((IEnumerable<SharpTreeNode>?)viewState.DecompiledNodes ?? Array.Empty<SharpTreeNode>());
ViewState = viewState; ViewState = viewState;
} }

4
ILSpy/Options/DisplaySettingsPanel.xaml.cs

@ -99,11 +99,11 @@ namespace ICSharpCode.ILSpy.Options
select ff).ToArray(); select ff).ToArray();
} }
public static DisplaySettings LoadDisplaySettings(ILSpySettings settings, SessionSettings sessionSettings = null) public static DisplaySettings LoadDisplaySettings(ILSpySettings settings, SessionSettings? sessionSettings = null)
{ {
XElement e = settings["DisplaySettings"]; XElement e = settings["DisplaySettings"];
var s = new DisplaySettings(); var s = new DisplaySettings();
s.SelectedFont = new FontFamily((string)e.Attribute("Font") ?? "Consolas"); s.SelectedFont = new FontFamily((string?)e.Attribute("Font") ?? "Consolas");
s.SelectedFontSize = (double?)e.Attribute("FontSize") ?? 10.0 * 4 / 3; s.SelectedFontSize = (double?)e.Attribute("FontSize") ?? 10.0 * 4 / 3;
s.ShowLineNumbers = (bool?)e.Attribute("ShowLineNumbers") ?? false; s.ShowLineNumbers = (bool?)e.Attribute("ShowLineNumbers") ?? false;
s.ShowMetadataTokens = (bool?)e.Attribute("ShowMetadataTokens") ?? false; s.ShowMetadataTokens = (bool?)e.Attribute("ShowMetadataTokens") ?? false;

4
ILSpy/Options/OptionsDialog.xaml.cs

@ -63,7 +63,7 @@ namespace ICSharpCode.ILSpy.Options
tabControl.Items.Add(tabItem); tabControl.Items.Add(tabItem);
IOptionPage page = optionPage.Value as IOptionPage; IOptionPage? page = optionPage.Value as IOptionPage;
if (page != null) if (page != null)
page.Load(settings); page.Load(settings);
} }
@ -75,7 +75,7 @@ namespace ICSharpCode.ILSpy.Options
delegate (XElement root) { delegate (XElement root) {
foreach (var optionPage in optionPages) foreach (var optionPage in optionPages)
{ {
IOptionPage page = optionPage.Value as IOptionPage; IOptionPage? page = optionPage.Value as IOptionPage;
if (page != null) if (page != null)
page.Save(root); page.Save(root);
} }

10
ILSpy/Search/SearchPane.xaml.cs

@ -53,7 +53,7 @@ namespace ICSharpCode.ILSpy.Search
{ {
const int MAX_RESULTS = 1000; const int MAX_RESULTS = 1000;
const int MAX_REFRESH_TIME_MS = 10; // More means quicker forward of data, fewer means better responsibility const int MAX_REFRESH_TIME_MS = 10; // More means quicker forward of data, fewer means better responsibility
RunningSearch currentSearch; RunningSearch? currentSearch;
bool runSearchOnNextShow; bool runSearchOnNextShow;
IComparer<SearchResult> resultsComparer; IComparer<SearchResult> resultsComparer;
@ -231,7 +231,7 @@ namespace ICSharpCode.ILSpy.Search
currentSearch.Cancel(); currentSearch.Cancel();
} }
async void StartSearch(string searchTerm) async void StartSearch(string? searchTerm)
{ {
if (currentSearch != null) if (currentSearch != null)
{ {
@ -245,7 +245,7 @@ namespace ICSharpCode.ILSpy.Search
SearchResult.ComparerByName; SearchResult.ComparerByName;
Results.Clear(); Results.Clear();
RunningSearch startedSearch = null; RunningSearch? startedSearch = null;
if (!string.IsNullOrEmpty(searchTerm)) if (!string.IsNullOrEmpty(searchTerm))
{ {
@ -299,7 +299,7 @@ namespace ICSharpCode.ILSpy.Search
SearchRequest request = new(); SearchRequest request = new();
List<string> keywords = new(); List<string> keywords = new();
Regex regex = null; Regex? regex = null;
request.Mode = searchMode; request.Mode = searchMode;
foreach (string part in parts) foreach (string part in parts)
@ -325,7 +325,7 @@ namespace ICSharpCode.ILSpy.Search
prefixLength = part.IndexOf(':', 0, prefixLength); prefixLength = part.IndexOf(':', 0, prefixLength);
delimiterLength = 1; delimiterLength = 1;
} }
string prefix; string? prefix;
if (prefixLength <= 0) if (prefixLength <= 0)
{ {
prefix = null; prefix = null;

12
ILSpy/SessionSettings.cs

@ -44,7 +44,7 @@ namespace ICSharpCode.ILSpy
{ {
XElement doc = spySettings["SessionSettings"]; XElement doc = spySettings["SessionSettings"];
XElement filterSettings = doc.Element("FilterSettings"); XElement? filterSettings = doc.Element("FilterSettings");
if (filterSettings == null) if (filterSettings == null)
filterSettings = new XElement("FilterSettings"); filterSettings = new XElement("FilterSettings");
@ -52,7 +52,7 @@ namespace ICSharpCode.ILSpy
this.ActiveAssemblyList = (string)doc.Element("ActiveAssemblyList"); this.ActiveAssemblyList = (string)doc.Element("ActiveAssemblyList");
XElement activeTreeViewPath = doc.Element("ActiveTreeViewPath"); XElement? activeTreeViewPath = doc.Element("ActiveTreeViewPath");
if (activeTreeViewPath != null) if (activeTreeViewPath != null)
{ {
this.ActiveTreeViewPath = activeTreeViewPath.Elements().Select(e => Unescape((string)e)).ToArray(); this.ActiveTreeViewPath = activeTreeViewPath.Elements().Select(e => Unescape((string)e)).ToArray();
@ -63,7 +63,7 @@ namespace ICSharpCode.ILSpy
this.WindowBounds = FromString((string)doc.Element("WindowBounds"), DefaultWindowBounds); this.WindowBounds = FromString((string)doc.Element("WindowBounds"), DefaultWindowBounds);
this.SelectedSearchMode = FromString((string)doc.Element("SelectedSearchMode"), SearchMode.TypeAndMember); this.SelectedSearchMode = FromString((string)doc.Element("SelectedSearchMode"), SearchMode.TypeAndMember);
this.Theme = FromString((string)doc.Element(nameof(Theme)), ThemeManager.Current.DefaultTheme); this.Theme = FromString((string)doc.Element(nameof(Theme)), ThemeManager.Current.DefaultTheme);
string currentCulture = (string)doc.Element(nameof(CurrentCulture)); string? currentCulture = (string)doc.Element(nameof(CurrentCulture));
this.CurrentCulture = string.IsNullOrEmpty(currentCulture) ? null : currentCulture; this.CurrentCulture = string.IsNullOrEmpty(currentCulture) ? null : currentCulture;
this.DockLayout = new DockLayoutSettings(doc.Element("DockLayout")); this.DockLayout = new DockLayoutSettings(doc.Element("DockLayout"));
@ -108,7 +108,7 @@ namespace ICSharpCode.ILSpy
} }
} }
public string ActiveAssemblyList { public string? ActiveAssemblyList {
get => activeAssemblyList; get => activeAssemblyList;
set { set {
if (value != null && value != activeAssemblyList) if (value != null && value != activeAssemblyList)
@ -166,7 +166,7 @@ namespace ICSharpCode.ILSpy
} }
static Regex regex = new Regex("\\\\x(?<num>[0-9A-f]{4})"); static Regex regex = new Regex("\\\\x(?<num>[0-9A-f]{4})");
private string activeAssemblyList; private string? activeAssemblyList;
static string Escape(string p) static string Escape(string p)
{ {
@ -186,7 +186,7 @@ namespace ICSharpCode.ILSpy
return regex.Replace(p, m => ((char)int.Parse(m.Groups["num"].Value, NumberStyles.HexNumber)).ToString()); return regex.Replace(p, m => ((char)int.Parse(m.Groups["num"].Value, NumberStyles.HexNumber)).ToString());
} }
static T FromString<T>(string s, T defaultValue) static T FromString<T>(string? s, T defaultValue)
{ {
if (s == null) if (s == null)
return defaultValue; return defaultValue;

2
ILSpy/TaskHelper.cs

@ -174,7 +174,7 @@ namespace ICSharpCode.ILSpy
return task.ContinueWith(t => { return task.ContinueWith(t => {
if (t.IsFaulted) if (t.IsFaulted)
{ {
Exception ex = t.Exception; Exception? ex = t.Exception;
while (ex is AggregateException) while (ex is AggregateException)
ex = ex.InnerException; ex = ex.InnerException;
if (ex is TException) if (ex is TException)

2
ILSpy/TextView/AvalonEditTextOutput.cs

@ -40,7 +40,7 @@ namespace ICSharpCode.ILSpy.TextView
/// </summary> /// </summary>
public sealed class ReferenceSegment : TextSegment public sealed class ReferenceSegment : TextSegment
{ {
public object Reference; public object? Reference;
public bool IsLocal; public bool IsLocal;
public bool IsDefinition; public bool IsDefinition;
} }

6
ILSpy/TextView/DecompilerTextView.cs

@ -392,7 +392,7 @@ namespace ICSharpCode.ILSpy.TextView
{ {
if (segment.Reference is ICSharpCode.Decompiler.Disassembler.OpCodeInfo code) if (segment.Reference is ICSharpCode.Decompiler.Disassembler.OpCodeInfo code)
{ {
XmlDocumentationProvider docProvider = XmlDocLoader.MscorlibDocumentation; XmlDocumentationProvider? docProvider = XmlDocLoader.MscorlibDocumentation;
DocumentationUIBuilder renderer = new DocumentationUIBuilder(new CSharpAmbience(), SettingsService.Instance.SessionSettings.LanguageSettings.Language.SyntaxHighlighting); DocumentationUIBuilder renderer = new DocumentationUIBuilder(new CSharpAmbience(), SettingsService.Instance.SessionSettings.LanguageSettings.Language.SyntaxHighlighting);
renderer.AddSignatureBlock($"{code.Name} (0x{code.Code:x})"); renderer.AddSignatureBlock($"{code.Name} (0x{code.Code:x})");
if (docProvider != null) if (docProvider != null)
@ -425,7 +425,7 @@ namespace ICSharpCode.ILSpy.TextView
Handle handle = unresolvedEntity.Handle; Handle handle = unresolvedEntity.Handle;
if (!handle.IsEntityHandle()) if (!handle.IsEntityHandle())
return null; return null;
IEntity resolved = typeSystem.MainModule.ResolveEntity((EntityHandle)handle); IEntity? resolved = typeSystem.MainModule.ResolveEntity((EntityHandle)handle);
if (resolved == null) if (resolved == null)
return null; return null;
var document = CreateTooltipForEntity(resolved); var document = CreateTooltipForEntity(resolved);
@ -445,7 +445,7 @@ namespace ICSharpCode.ILSpy.TextView
{ {
Language currentLanguage = SettingsService.Instance.SessionSettings.LanguageSettings.Language; Language currentLanguage = SettingsService.Instance.SessionSettings.LanguageSettings.Language;
DocumentationUIBuilder renderer = new DocumentationUIBuilder(new CSharpAmbience(), currentLanguage.SyntaxHighlighting); DocumentationUIBuilder renderer = new DocumentationUIBuilder(new CSharpAmbience(), currentLanguage.SyntaxHighlighting);
RichText richText = currentLanguage.GetRichTextTooltip(resolved); RichText? richText = currentLanguage.GetRichTextTooltip(resolved);
if (richText == null) if (richText == null)
{ {
return null; return null;

6
ILSpy/TextView/DocumentationUIBuilder.cs

@ -128,7 +128,7 @@ namespace ICSharpCode.ILSpy.TextView
AddBlock(block); AddBlock(block);
} }
public void AddXmlDocumentation(string xmlDocumentation, IEntity declaringEntity, Func<string, IEntity?> resolver) public void AddXmlDocumentation(string xmlDocumentation, IEntity? declaringEntity, Func<string, IEntity?>? resolver)
{ {
if (xmlDocumentation == null) if (xmlDocumentation == null)
return; return;
@ -375,7 +375,7 @@ namespace ICSharpCode.ILSpy.TextView
void AddSee(XmlDocumentationElement element) void AddSee(XmlDocumentationElement element)
{ {
IEntity referencedEntity = element.ReferencedEntity; IEntity? referencedEntity = element.ReferencedEntity;
if (referencedEntity != null) if (referencedEntity != null)
{ {
if (element.Children.Any()) if (element.Children.Any())
@ -397,7 +397,7 @@ namespace ICSharpCode.ILSpy.TextView
} }
else if (element.GetAttribute("href") != null) else if (element.GetAttribute("href") != null)
{ {
Uri uri; Uri? uri;
if (Uri.TryCreate(element.GetAttribute("href"), UriKind.Absolute, out uri)) if (Uri.TryCreate(element.GetAttribute("href"), UriKind.Absolute, out uri))
{ {
if (element.Children.Any()) if (element.Children.Any())

6
ILSpy/TextView/FoldingCommands.cs

@ -43,7 +43,7 @@ namespace ICSharpCode.ILSpy.TextView
{ {
if (null == context.TextView) if (null == context.TextView)
return; return;
FoldingManager foldingManager = context.TextView.FoldingManager; FoldingManager? foldingManager = context.TextView.FoldingManager;
if (null == foldingManager) if (null == foldingManager)
return; return;
bool doFold = true; bool doFold = true;
@ -82,7 +82,7 @@ namespace ICSharpCode.ILSpy.TextView
if (null == textView) if (null == textView)
return; return;
var editor = textView.textEditor; var editor = textView.textEditor;
FoldingManager foldingManager = context.TextView.FoldingManager; FoldingManager? foldingManager = context.TextView.FoldingManager;
if (null == foldingManager) if (null == foldingManager)
return; return;
// TODO: or use Caret if position is not given? // TODO: or use Caret if position is not given?
@ -91,7 +91,7 @@ namespace ICSharpCode.ILSpy.TextView
return; return;
TextViewPosition pos = posBox.Value; TextViewPosition pos = posBox.Value;
// look for folding on this line: // look for folding on this line:
FoldingSection folding = foldingManager.GetNextFolding(editor.Document.GetOffset(pos.Line, 1)); FoldingSection? folding = foldingManager.GetNextFolding(editor.Document.GetOffset(pos.Line, 1));
if (folding == null || editor.Document.GetLineByOffset(folding.StartOffset).LineNumber != pos.Line) if (folding == null || editor.Document.GetLineByOffset(folding.StartOffset).LineNumber != pos.Line)
{ {
// no folding found on current line: find innermost folding containing the mouse position // no folding found on current line: find innermost folding containing the mouse position

16
ILSpy/TreeNodes/AssemblyListTreeNode.cs

@ -98,7 +98,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
public override void Drop(IPlatformDragEventArgs e, int index) public override void Drop(IPlatformDragEventArgs e, int index)
{ {
string[] files = e.Data.GetData(AssemblyTreeNode.DataFormat) as string[]; string[]? files = e.Data.GetData(AssemblyTreeNode.DataFormat) as string[];
if (files == null) if (files == null)
files = e.Data.GetData(DataFormats.FileDrop) as string[]; files = e.Data.GetData(DataFormats.FileDrop) as string[];
if (files != null) if (files != null)
@ -225,7 +225,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
var declaringType = def.DeclaringTypeDefinition; var declaringType = def.DeclaringTypeDefinition;
if (declaringType != null) if (declaringType != null)
{ {
TypeTreeNode decl = FindTypeNode(declaringType); TypeTreeNode? decl = FindTypeNode(declaringType);
if (decl != null) if (decl != null)
{ {
decl.EnsureLazyChildren(); decl.EnsureLazyChildren();
@ -249,12 +249,12 @@ namespace ICSharpCode.ILSpy.TreeNodes
/// </summary> /// </summary>
public ILSpyTreeNode? FindMethodNode(IMethod def) public ILSpyTreeNode? FindMethodNode(IMethod def)
{ {
TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition);
if (typeNode == null) if (typeNode == null)
return null; return null;
// method might be an accessor, must look for parent node // method might be an accessor, must look for parent node
ILSpyTreeNode parentNode = typeNode; ILSpyTreeNode? parentNode = typeNode;
MethodTreeNode methodNode; MethodTreeNode? methodNode;
parentNode.EnsureLazyChildren(); parentNode.EnsureLazyChildren();
switch (def.AccessorOwner) switch (def.AccessorOwner)
{ {
@ -290,7 +290,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
/// </summary> /// </summary>
public FieldTreeNode? FindFieldNode(IField def) public FieldTreeNode? FindFieldNode(IField def)
{ {
TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition);
if (typeNode == null) if (typeNode == null)
return null; return null;
typeNode.EnsureLazyChildren(); typeNode.EnsureLazyChildren();
@ -303,7 +303,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
/// </summary> /// </summary>
public PropertyTreeNode? FindPropertyNode(IProperty def) public PropertyTreeNode? FindPropertyNode(IProperty def)
{ {
TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition);
if (typeNode == null) if (typeNode == null)
return null; return null;
typeNode.EnsureLazyChildren(); typeNode.EnsureLazyChildren();
@ -316,7 +316,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
/// </summary> /// </summary>
public EventTreeNode? FindEventNode(IEvent def) public EventTreeNode? FindEventNode(IEvent def)
{ {
TypeTreeNode typeNode = FindTypeNode(def.DeclaringTypeDefinition); TypeTreeNode? typeNode = FindTypeNode(def.DeclaringTypeDefinition);
if (typeNode == null) if (typeNode == null)
return null; return null;
typeNode.EnsureLazyChildren(); typeNode.EnsureLazyChildren();

8
ILSpy/TreeNodes/AssemblyTreeNode.cs

@ -248,7 +248,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
typeSystem = LoadedAssembly.GetTypeSystemOrNull(); typeSystem = LoadedAssembly.GetTypeSystemOrNull();
var assembly = (MetadataModule)typeSystem.MainModule; var assembly = (MetadataModule)typeSystem.MainModule;
this.Children.Add(new MetadataTreeNode(module, Resources.Metadata)); this.Children.Add(new MetadataTreeNode(module, Resources.Metadata));
Decompiler.DebugInfo.IDebugInfoProvider debugInfo = LoadedAssembly.GetDebugInfoOrNull(); Decompiler.DebugInfo.IDebugInfoProvider? debugInfo = LoadedAssembly.GetDebugInfoOrNull();
if (debugInfo is PortableDebugInfoProvider ppdb if (debugInfo is PortableDebugInfoProvider ppdb
&& ppdb.GetMetadataReader() is System.Reflection.Metadata.MetadataReader reader) && ppdb.GetMetadataReader() is System.Reflection.Metadata.MetadataReader reader)
{ {
@ -280,7 +280,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace) NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace)
{ {
if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns)) if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode? ns))
{ {
if (useNestedStructure) if (useNestedStructure)
{ {
@ -346,7 +346,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace) NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace)
{ {
if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns)) if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode? ns))
{ {
if (useNestedStructure) if (useNestedStructure)
{ {
@ -392,7 +392,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
if (type == null) if (type == null)
return null; return null;
EnsureLazyChildren(); EnsureLazyChildren();
TypeTreeNode node; TypeTreeNode? node;
if (typeDict.TryGetValue((TypeDefinitionHandle)type.MetadataToken, out node)) if (typeDict.TryGetValue((TypeDefinitionHandle)type.MetadataToken, out node))
return node; return node;
else else

6
ILSpy/TreeNodes/ResourceNodes/ResourceTreeNode.cs

@ -71,7 +71,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
var sizeInBytesText = sizeInBytes == null ? "" : ", " + sizeInBytes + " bytes"; var sizeInBytesText = sizeInBytes == null ? "" : ", " + sizeInBytes + " bytes";
language.WriteCommentLine(output, $"{Resource.Name} ({Resource.ResourceType}, {Resource.Attributes}{sizeInBytesText})"); language.WriteCommentLine(output, $"{Resource.Name} ({Resource.ResourceType}, {Resource.Attributes}{sizeInBytesText})");
ISmartTextOutput smartOutput = output as ISmartTextOutput; ISmartTextOutput? smartOutput = output as ISmartTextOutput;
if (smartOutput != null) if (smartOutput != null)
{ {
smartOutput.AddButton(Images.Save, Resources.Save, delegate { Save(Docking.DockWorkspace.Instance.ActiveTabPage); }); smartOutput.AddButton(Images.Save, Resources.Save, delegate { Save(Docking.DockWorkspace.Instance.ActiveTabPage); });
@ -81,7 +81,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
public override bool View(TabPageModel tabPage) public override bool View(TabPageModel tabPage)
{ {
Stream s = Resource.TryOpenStream(); Stream? s = Resource.TryOpenStream();
if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit) if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit)
{ {
s.Position = 0; s.Position = 0;
@ -107,7 +107,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
public override bool Save(TabPageModel tabPage) public override bool Save(TabPageModel tabPage)
{ {
Stream s = Resource.TryOpenStream(); Stream? s = Resource.TryOpenStream();
if (s == null) if (s == null)
return false; return false;
SaveFileDialog dlg = new SaveFileDialog(); SaveFileDialog dlg = new SaveFileDialog();

8
ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs

@ -71,7 +71,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
protected override void LoadChildren() protected override void LoadChildren()
{ {
Stream s = Resource.TryOpenStream(); Stream? s = Resource.TryOpenStream();
if (s == null) if (s == null)
return; return;
s.Position = 0; s.Position = 0;
@ -128,7 +128,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
public override bool Save(TabPageModel tabPage) public override bool Save(TabPageModel tabPage)
{ {
Stream s = Resource.TryOpenStream(); Stream? s = Resource.TryOpenStream();
if (s == null) if (s == null)
return false; return false;
SaveFileDialog dlg = new SaveFileDialog(); SaveFileDialog dlg = new SaveFileDialog();
@ -179,7 +179,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
var textView = (DecompilerTextView)Docking.DockWorkspace.Instance.ActiveTabPage.Content; var textView = (DecompilerTextView)Docking.DockWorkspace.Instance.ActiveTabPage.Content;
if (stringTableEntries.Count != 0) if (stringTableEntries.Count != 0)
{ {
ISmartTextOutput smartOutput = output as ISmartTextOutput; ISmartTextOutput? smartOutput = output as ISmartTextOutput;
if (null != smartOutput) if (null != smartOutput)
{ {
smartOutput.AddUIElement( smartOutput.AddUIElement(
@ -193,7 +193,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
} }
if (otherEntries.Count != 0) if (otherEntries.Count != 0)
{ {
ISmartTextOutput smartOutput = output as ISmartTextOutput; ISmartTextOutput? smartOutput = output as ISmartTextOutput;
if (null != smartOutput) if (null != smartOutput)
{ {
smartOutput.AddUIElement( smartOutput.AddUIElement(

2
ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs

@ -54,7 +54,7 @@ namespace ICSharpCode.ILSpy.Xaml
public override bool View(TabPageModel tabPage) public override bool View(TabPageModel tabPage)
{ {
AvalonEditTextOutput output = new AvalonEditTextOutput(); AvalonEditTextOutput output = new AvalonEditTextOutput();
IHighlightingDefinition highlighting = null; IHighlightingDefinition? highlighting = null;
tabPage.ShowTextView(textView => textView.RunWithCancellation( tabPage.ShowTextView(textView => textView.RunWithCancellation(
token => Task.Factory.StartNew( token => Task.Factory.StartNew(

2
ILSpy/TreeNodes/ThreadingSupport.cs

@ -67,7 +67,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
CancellationToken ct = cancellationTokenSource.Token; CancellationToken ct = cancellationTokenSource.Token;
var fetchChildrenEnumerable = fetchChildren(ct); var fetchChildrenEnumerable = fetchChildren(ct);
Task<List<SharpTreeNode>> thisTask = null; Task<List<SharpTreeNode>>? thisTask = null;
thisTask = new Task<List<SharpTreeNode>>( thisTask = new Task<List<SharpTreeNode>>(
delegate { delegate {
List<SharpTreeNode> result = new List<SharpTreeNode>(); List<SharpTreeNode> result = new List<SharpTreeNode>();

2
ILSpy/Updates/NotifyOfUpdatesStrategy.cs

@ -46,7 +46,7 @@ namespace ICSharpCode.ILSpy.Updates
var bands = doc.Root.Elements("band"); var bands = doc.Root.Elements("band");
var currentBand = bands.FirstOrDefault(b => (string)b.Attribute("id") == band) ?? bands.First(); var currentBand = bands.FirstOrDefault(b => (string)b.Attribute("id") == band) ?? bands.First();
Version version = new Version((string)currentBand.Element("latestVersion")); Version version = new Version((string)currentBand.Element("latestVersion"));
string url = (string)currentBand.Element("downloadUrl"); string? url = (string)currentBand.Element("downloadUrl");
if (!(url.StartsWith("http://", StringComparison.Ordinal) || url.StartsWith("https://", StringComparison.Ordinal))) if (!(url.StartsWith("http://", StringComparison.Ordinal) || url.StartsWith("https://", StringComparison.Ordinal)))
url = null; // don't accept non-urls url = null; // don't accept non-urls

2
TestPlugin/CustomLanguage.cs

@ -41,7 +41,7 @@ namespace TestPlugin
var methodBody = module.GetMethodBody(methodDef.RelativeVirtualAddress); var methodBody = module.GetMethodBody(methodDef.RelativeVirtualAddress);
output.WriteLine("Size of method: {0} bytes", methodBody.GetCodeSize()); output.WriteLine("Size of method: {0} bytes", methodBody.GetCodeSize());
ISmartTextOutput smartOutput = output as ISmartTextOutput; ISmartTextOutput? smartOutput = output as ISmartTextOutput;
if (smartOutput != null) if (smartOutput != null)
{ {
// when writing to the text view (but not when writing to a file), we can even add UI elements such as buttons: // when writing to the text view (but not when writing to a file), we can even add UI elements such as buttons:

2
TestPlugin/CustomOptionPage.xaml.cs

@ -50,7 +50,7 @@ namespace TestPlugin
// Replace the existing section in the settings file, or add a new section, // Replace the existing section in the settings file, or add a new section,
// if required. // if required.
XElement existingElement = root.Element(ns + "CustomOptions"); XElement? existingElement = root.Element(ns + "CustomOptions");
if (existingElement != null) if (existingElement != null)
existingElement.ReplaceWith(section); existingElement.ReplaceWith(section);
else else

Loading…
Cancel
Save