Skip to content

Commit

Permalink
Replace typeof(X).Name with nameof(X) #1077
Browse files Browse the repository at this point in the history
* Replaced all occurrences of typeof(X).Name with nameof(X)

* Improved code readability and compile-time safety
  • Loading branch information
manognya-b committed Jan 6, 2025
1 parent 705a288 commit 6435a2c
Show file tree
Hide file tree
Showing 20 changed files with 37 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public override Tokenizer Create(AttributeSource.AttributeFactory factory, TextR
EdgeNGramTokenFilter.Side sideEnum;
if (!Enum.TryParse(this.side, true, out sideEnum))
{
throw new ArgumentException(typeof(EdgeNGramTokenizer).Name + " does not support backward n-grams as of Lucene 4.4");
throw new ArgumentException(nameof(EdgeNGramTokenizer) + " does not support backward n-grams as of Lucene 4.4");
}
return new EdgeNGramTokenizer(m_luceneMatchVersion, input, minGramSize, maxGramSize);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ internal sealed class AnalysisSPILoader<S> where S : AbstractAnalysisFactory
private readonly string[] suffixes;

public AnalysisSPILoader()
: this(new string[] { typeof(S).Name })
: this(new string[] { nameof(S) })
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public void Write(string baseDir)
// LUCENENET specific: we don't need to do a "classpath" output directory, since we
// are changing the implementation to read files dynamically instead of making the
// user recompile with the new files.
string filename = System.IO.Path.Combine(baseDir, typeof(CharacterDefinition).Name + CharacterDefinition.FILENAME_SUFFIX);
string filename = System.IO.Path.Combine(baseDir, nameof(CharacterDefinition) + CharacterDefinition.FILENAME_SUFFIX);
//new File(filename).getParentFile().mkdirs();
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(baseDir));
using Stream os = new FileStream(filename, FileMode.Create, FileAccess.Write);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ private long GetNextCounter()

public virtual void SetConfig(Config config)
{
Analyzer anlzr = NewAnalyzerTask.CreateAnalyzer(config.Get("analyzer", typeof(StandardAnalyzer).Name));
Analyzer anlzr = NewAnalyzerTask.CreateAnalyzer(config.Get("analyzer", nameof(StandardAnalyzer)));
m_parser = new QueryParser(
#pragma warning disable 612, 618
LuceneVersion.LUCENE_CURRENT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,6 @@ public abstract class QueryTreeBuilder
/// This tag is used to tag the nodes in a query tree with the built objects
/// produced from their own associated builder.
/// </summary>
public static readonly string QUERY_TREE_BUILDER_TAGID = typeof(QueryTreeBuilder).Name;
public static readonly string QUERY_TREE_BUILDER_TAGID = nameof(QueryTreeBuilder);
}
}
4 changes: 2 additions & 2 deletions src/Lucene.Net.Suggest/Suggest/Fst/FSTCompletionLookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ public override void Build(IInputEnumerator enumerator)
{
throw new ArgumentException("this suggester doesn't support contexts");
}
using FileStream tempInput = FileSupport.CreateTempFileAsStream(typeof(FSTCompletionLookup).Name, ".input", OfflineSorter.DefaultTempDir);
using FileStream tempSorted = FileSupport.CreateTempFileAsStream(typeof(FSTCompletionLookup).Name, ".sorted", OfflineSorter.DefaultTempDir);
using FileStream tempInput = FileSupport.CreateTempFileAsStream(nameof(FSTCompletionLookup), ".input", OfflineSorter.DefaultTempDir);
using FileStream tempSorted = FileSupport.CreateTempFileAsStream(nameof(FSTCompletionLookup), ".sorted", OfflineSorter.DefaultTempDir);

OfflineSorter.ByteSequencesWriter writer = new OfflineSorter.ByteSequencesWriter(tempInput);
OfflineSorter.ByteSequencesReader reader = null;
Expand Down
4 changes: 2 additions & 2 deletions src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,7 @@ private static IList<string> LoadCoreDirectories()
//// }
//// else
//// {
//// Console.Out.Write(typeof(LuceneTestCase).Name + " WARNING: Property '" + SYSPROP_MAXFAILURES + "'=" + maxFailures + ", 'failfast' is" + " ignored.");
//// Console.Out.Write(nameof(LuceneTestCase) + " WARNING: Property '" + SYSPROP_MAXFAILURES + "'=" + maxFailures + ", 'failfast' is" + " ignored.");
//// }
//// }

Expand Down Expand Up @@ -786,7 +786,7 @@ private static IList<string> LoadCoreDirectories()

/////// <summary>
/////// By-name list of ignored types like loggers etc. </summary>
//////private static ISet<string> STATIC_LEAK_IGNORED_TYPES = new JCG.HashSet<string>(new string[] { "org.slf4j.Logger", "org.apache.solr.SolrLogFormatter", typeof(EnumSet).Name });
//////private static ISet<string> STATIC_LEAK_IGNORED_TYPES = new JCG.HashSet<string>(new string[] { "org.slf4j.Logger", "org.apache.solr.SolrLogFormatter", nameof(EnumSet) });

/////// <summary>
/////// this controls how suite-level rules are nested. It is important that _all_ rules declared
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net.TestFramework/Util/TestSecurityManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public PrivilegedActionAnonymousClass(TestSecurityManager outerInstance, int sta

public override void Run()
{
const string systemClassName = typeof(System).Name, runtimeClassName = typeof(Runtime).Name;
const string systemClassName = nameof(System), runtimeClassName = nameof(Runtime);
string exitMethodHit = null;
foreach (StackTraceElement se in Thread.CurrentThread.StackTrace)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

// public class MessagesTestBundle : NLS
// {
// private static readonly string BUNDLE_NAME = typeof(MessagesTestBundle).Name;
// private static readonly string BUNDLE_NAME = nameof(MessagesTestBundle);

// private MessagesTestBundle()
// {
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net.Tests/Index/TestIndexWriterWithThreads.cs
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ public override void Eval(MockDirectoryWrapper dir)
{
// LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
// to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
if (StackTraceHelper.DoesStackTraceContainMethod(typeof(DocFieldProcessor).Name, "Flush"))
if (StackTraceHelper.DoesStackTraceContainMethod(nameof(DocFieldProcessor), "Flush"))
{
if (onlyOnce)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net.Tests/Search/TestBooleanScorer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public void SetScorer(Scorer scorer)
{
// Make sure we got BooleanScorer:
Type clazz = scorer.GetType();
Assert.AreEqual(typeof(FakeScorer).Name, clazz.Name, "Scorer is implemented by wrong class");
Assert.AreEqual(nameof(FakeScorer), clazz.Name, "Scorer is implemented by wrong class");
}

public void Collect(int doc)
Expand Down
8 changes: 4 additions & 4 deletions src/Lucene.Net.Tests/Search/TestConstantScoreQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,13 @@ public virtual void TestWrapped2Times()
Query csqbq = new ConstantScoreQuery(bq);
csqbq.Boost = 17.0f;

CheckHits(searcher, csq1, csq1.Boost, typeof(ConstantScoreQuery.ConstantScorer).Name, null);
CheckHits(searcher, csq2, csq2.Boost, typeof(ConstantScoreQuery.ConstantScorer).Name, typeof(ConstantScoreQuery.ConstantScorer).Name);
CheckHits(searcher, csq1, csq1.Boost, nameof(ConstantScoreQuery.ConstantScorer), null);
CheckHits(searcher, csq2, csq2.Boost, nameof(ConstantScoreQuery.ConstantScorer), nameof(ConstantScoreQuery.ConstantScorer));

// for the combined BQ, the scorer should always be BooleanScorer's BucketScorer, because our scorer supports out-of order collection!
string bucketScorerClass = typeof(FakeScorer).Name;
string bucketScorerClass = nameof(FakeScorer);
CheckHits(searcher, bq, csq1.Boost + csq2.Boost, bucketScorerClass, null);
CheckHits(searcher, csqbq, csqbq.Boost, typeof(ConstantScoreQuery.ConstantScorer).Name, bucketScorerClass);
CheckHits(searcher, csqbq, csqbq.Boost, nameof(ConstantScoreQuery.ConstantScorer), bucketScorerClass);
}
finally
{
Expand Down
10 changes: 5 additions & 5 deletions src/Lucene.Net/Codecs/Lucene3x/Lucene3xSegmentInfoFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ public class Lucene3xSegmentInfoFormat : SegmentInfoFormat
public override SegmentInfoWriter SegmentInfoWriter => throw UnsupportedOperationException.Create("this codec can only be used for reading");

// only for backwards compat
public static readonly string DS_OFFSET_KEY = typeof(Lucene3xSegmentInfoFormat).Name + ".dsoffset";
public static readonly string DS_OFFSET_KEY = nameof(Lucene3xSegmentInfoFormat) + ".dsoffset";

public static readonly string DS_NAME_KEY = typeof(Lucene3xSegmentInfoFormat).Name + ".dsname";
public static readonly string DS_COMPOUND_KEY = typeof(Lucene3xSegmentInfoFormat).Name + ".dscompound";
public static readonly string NORMGEN_KEY = typeof(Lucene3xSegmentInfoFormat).Name + ".normgen";
public static readonly string NORMGEN_PREFIX = typeof(Lucene3xSegmentInfoFormat).Name + ".normfield";
public static readonly string DS_NAME_KEY = nameof(Lucene3xSegmentInfoFormat) + ".dsname";
public static readonly string DS_COMPOUND_KEY = nameof(Lucene3xSegmentInfoFormat) + ".dscompound";
public static readonly string NORMGEN_KEY = nameof(Lucene3xSegmentInfoFormat) + ".normgen";
public static readonly string NORMGEN_PREFIX = nameof(Lucene3xSegmentInfoFormat) + ".normfield";

/// <returns> If this segment shares stored fields &amp; vectors, this
/// offset is where in that file this segment's docs begin. </returns>
Expand Down
4 changes: 2 additions & 2 deletions src/Lucene.Net/Codecs/Lucene40/Lucene40FieldInfosReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ public override FieldInfos Read(Directory directory, string segmentName, string
}
}

internal static readonly string LEGACY_DV_TYPE_KEY = typeof(Lucene40FieldInfosReader).Name + ".dvtype";
internal static readonly string LEGACY_NORM_TYPE_KEY = typeof(Lucene40FieldInfosReader).Name + ".normtype";
internal static readonly string LEGACY_DV_TYPE_KEY = nameof(Lucene40FieldInfosReader) + ".dvtype";
internal static readonly string LEGACY_NORM_TYPE_KEY = nameof(Lucene40FieldInfosReader) + ".normtype";

// mapping of 4.0 types -> 4.2 types
/*internal enum LegacyDocValuesType
Expand Down
4 changes: 2 additions & 2 deletions src/Lucene.Net/Codecs/PerField/PerFieldDocValuesFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ public abstract class PerFieldDocValuesFormat : DocValuesFormat
/// <see cref="FieldInfo"/> attribute name used to store the
/// format name for each field.
/// </summary>
public static readonly string PER_FIELD_FORMAT_KEY = typeof(PerFieldDocValuesFormat).Name + ".format";
public static readonly string PER_FIELD_FORMAT_KEY = nameof(PerFieldDocValuesFormat) + ".format";

/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// segment suffix name for each field.
/// </summary>
public static readonly string PER_FIELD_SUFFIX_KEY = typeof(PerFieldDocValuesFormat).Name + ".suffix";
public static readonly string PER_FIELD_SUFFIX_KEY = nameof(PerFieldDocValuesFormat) + ".suffix";

/// <summary>
/// Sole constructor. </summary>
Expand Down
4 changes: 2 additions & 2 deletions src/Lucene.Net/Codecs/PerField/PerFieldPostingsFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ public abstract class PerFieldPostingsFormat : PostingsFormat
/// <see cref="FieldInfo"/> attribute name used to store the
/// format name for each field.
/// </summary>
public static readonly string PER_FIELD_FORMAT_KEY = typeof(PerFieldPostingsFormat).Name + ".format";
public static readonly string PER_FIELD_FORMAT_KEY = nameof(PerFieldPostingsFormat) + ".format";

/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// segment suffix name for each field.
/// </summary>
public static readonly string PER_FIELD_SUFFIX_KEY = typeof(PerFieldPostingsFormat).Name + ".suffix";
public static readonly string PER_FIELD_SUFFIX_KEY = nameof(PerFieldPostingsFormat) + ".suffix";

/// <summary>
/// Sole constructor. </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net/Index/CheckIndex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2449,7 +2449,7 @@ public static void Main(string[] args)
// LUCENENET specific - we only output from our CLI wrapper
throw new ArgumentException("\nERROR: index path not specified");
//Console.WriteLine("\nERROR: index path not specified");
//Console.WriteLine("\nUsage: java Lucene.Net.Index.CheckIndex pathToIndex [-fix] [-crossCheckTermVectors] [-segment X] [-segment Y] [-dir-impl X]\n" + "\n" + " -fix: actually write a new segments_N file, removing any problematic segments\n" + " -crossCheckTermVectors: verifies that term vectors match postings; this IS VERY SLOW!\n" + " -codec X: when fixing, codec to write the new segments_N file with\n" + " -verbose: print additional details\n" + " -segment X: only check the specified segments. this can be specified multiple\n" + " times, to check more than one segment, eg '-segment _2 -segment _a'.\n" + " You can't use this with the -fix option\n" + " -dir-impl X: use a specific " + typeof(FSDirectory).Name + " implementation. " + "If no package is specified the " + typeof(FSDirectory).Namespace + " package will be used.\n" + "\n" + "**WARNING**: -fix should only be used on an emergency basis as it will cause\n" + "documents (perhaps many) to be permanently removed from the index. Always make\n" + "a backup copy of your index before running this! Do not run this tool on an index\n" + "that is actively being written to. You have been warned!\n" + "\n" + "Run without -fix, this tool will open the index, report version information\n" + "and report any exceptions it hits and what action it would take if -fix were\n" + "specified. With -fix, this tool will remove any segments that have issues and\n" + "write a new segments_N file. this means all documents contained in the affected\n" + "segments will be removed.\n" + "\n" + "this tool exits with exit code 1 if the index cannot be opened or has any\n" + "corruption, else 0.\n");
//Console.WriteLine("\nUsage: java Lucene.Net.Index.CheckIndex pathToIndex [-fix] [-crossCheckTermVectors] [-segment X] [-segment Y] [-dir-impl X]\n" + "\n" + " -fix: actually write a new segments_N file, removing any problematic segments\n" + " -crossCheckTermVectors: verifies that term vectors match postings; this IS VERY SLOW!\n" + " -codec X: when fixing, codec to write the new segments_N file with\n" + " -verbose: print additional details\n" + " -segment X: only check the specified segments. this can be specified multiple\n" + " times, to check more than one segment, eg '-segment _2 -segment _a'.\n" + " You can't use this with the -fix option\n" + " -dir-impl X: use a specific " + nameof(FSDirectory) + " implementation. " + "If no package is specified the " + typeof(FSDirectory).Namespace + " package will be used.\n" + "\n" + "**WARNING**: -fix should only be used on an emergency basis as it will cause\n" + "documents (perhaps many) to be permanently removed from the index. Always make\n" + "a backup copy of your index before running this! Do not run this tool on an index\n" + "that is actively being written to. You have been warned!\n" + "\n" + "Run without -fix, this tool will open the index, report version information\n" + "and report any exceptions it hits and what action it would take if -fix were\n" + "specified. With -fix, this tool will remove any segments that have issues and\n" + "write a new segments_N file. this means all documents contained in the affected\n" + "segments will be removed.\n" + "\n" + "this tool exits with exit code 1 if the index cannot be opened or has any\n" + "corruption, else 0.\n");
//Environment.Exit(1);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Lucene.Net/Index/IndexUpgrader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ private static void PrintUsage()
throw new ArgumentException("One or more arguments was invalid");
//Console.Error.WriteLine("Upgrades an index so all segments created with a previous Lucene version are rewritten.");
//Console.Error.WriteLine("Usage:");
//Console.Error.WriteLine(" java " + typeof(IndexUpgrader).Name + " [-delete-prior-commits] [-verbose] [-dir-impl X] indexDir");
//Console.Error.WriteLine(" java " + nameof(IndexUpgrader) + " [-delete-prior-commits] [-verbose] [-dir-impl X] indexDir");
//Console.Error.WriteLine("this tool keeps only the last commit in an index; for this");
//Console.Error.WriteLine("reason, if the incoming index has more than one commit, the tool");
//Console.Error.WriteLine("refuses to run by default. Specify -delete-prior-commits to override");
//Console.Error.WriteLine("this, allowing the tool to delete all but the last commit.");
//Console.Error.WriteLine("Specify a " + typeof(FSDirectory).Name + " implementation through the -dir-impl option to force its use. If no package is specified the " + typeof(FSDirectory).Namespace + " package will be used.");
//Console.Error.WriteLine("Specify a " + nameof(FSDirectory) + " implementation through the -dir-impl option to force its use. If no package is specified the " + typeof(FSDirectory).Namespace + " package will be used.");
//Console.Error.WriteLine("WARNING: this tool may reorder document IDs!");
//Environment.FailFast("1");
}
Expand Down
2 changes: 1 addition & 1 deletion src/Lucene.Net/Support/Util/NamedServiceFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ protected static string GetCanonicalName(Type type)
genericSuffix = "Generic" + name.Substring(genericIndex + 1);
name = name.Substring(0, genericIndex);
}
string serviceName = typeof(TService).Name;
string serviceName = nameof(TService);
if (name.EndsWith(serviceName, StringComparison.Ordinal))
{
name = name.Substring(0, name.Length - serviceName.Length);
Expand Down
10 changes: 5 additions & 5 deletions src/Lucene.Net/Util/CommandLineUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,21 @@ public static FSDirectory NewFSDirectory(string clazzName, DirectoryInfo dir)

// LUCENENET: In .NET, we get a null when the class is not found, so we need to throw here for compatibility
if (clazz is null)
throw new ArgumentException(typeof(FSDirectory).Name + " implementation not found: " + clazzName);
throw new ArgumentException(nameof(FSDirectory) + " implementation not found: " + clazzName);

return NewFSDirectory(clazz, dir);
}
catch (Exception e) when (e.IsClassNotFoundException())
{
throw new ArgumentException(typeof(FSDirectory).Name + " implementation not found: " + clazzName, e);
throw new ArgumentException(nameof(FSDirectory) + " implementation not found: " + clazzName, e);
}
catch (Exception e) when (e.IsClassCastException())
{
throw new ArgumentException(clazzName + " is not a " + typeof(FSDirectory).Name + " implementation", e);
throw new ArgumentException(clazzName + " is not a " + nameof(FSDirectory) + " implementation", e);
}
catch (Exception e) when (e.IsNoSuchMethodException())
{
throw new ArgumentException(clazzName + " constructor with " + typeof(FileInfo).Name + " as parameter not found", e);
throw new ArgumentException(clazzName + " constructor with " + nameof(FileInfo) + " as parameter not found", e);
}
catch (Exception e)
{
Expand Down Expand Up @@ -91,7 +91,7 @@ private static string AdjustDirectoryClassName(string clazzName)
{
if (clazzName is null || clazzName.Trim().Length == 0)
{
throw new ArgumentException("The " + typeof(FSDirectory).Name + " implementation cannot be null or empty");
throw new ArgumentException("The " + nameof(FSDirectory) + " implementation cannot be null or empty");
}

// LUCENENET specific: Changed to use char rather than string so we get StringComparison.Ordinal,
Expand Down

0 comments on commit 6435a2c

Please sign in to comment.