I am trying to teach myself this so I am sure this is obvious.
I am trying to create 2 classes that I can call instances of in Program/Main. One class is a string to double tryparse method and the other will just hold variables that will be used for many things.
My problem is I can only set Main up without error if the Main Method is only holding my new instance of class statements so I am exiting code immediately.
I will post the code to the Main. Newbie code and question, any help is much appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SetupMath
{
class Program
{
public static void Main(string[] args)
//Bringing in classes to inherit methods from
{
StringToDouble IntakeParse = new StringToDouble();
SetUpVar GuitAction = new SetUpVar();
}
// new instance of the StringToDouble class
// getting variable value "action" from string to double tryparse
public class StringToDouble
{
public string action { get; set; }
//converting "action" variable to "what"
public string What
{
get { return this.action; }
set { this.action = value; }
}
}
public class SetUpVar // new instance of the SetVar class
{
public string GuitAction { get; set; }
public string What { get; set; }
//Do something code
public void Work()
{
Console.WriteLine("Please enter a number", GuitAction);
What = Console.ReadLine();
Console.WriteLine("You entered: " + What);
}
}
}
}
You are writing StringToDouble and SetUpVar classes inside the Program class scope that's why they are visible only there. If you want your classes to be visible inside the whole namespace you should write them outside of Program class
Related
I want to add Debug and Trace to a class that I've created. However, I don't know where in my code to initialize a Trace Listener.
Here is the code I want to add to my static class:
Trace.Listeners.Add(
new TextWriterTraceListener(
File.CreateText("log.txt")
)
);
Trace.AutoFlush = true;
Here is the class to which I want to add the Trace Listener:
using System;
using System.Diagnostics;
using System.IO;
namespace Example.Shared
{
public static class ExampleClass
{
public static string SaySomething()
{
Trace.WriteLine($"I'm gonna say something");
return "Something";
}
// etc.
}
}
Apart from this class, I have only created some unit tests using Xunit. I have not yet created the application that will use this class.
This is what the unit test code looks like:
using Example.Shared;
using Xunit;
namespace ClassLibTests
{
public class ExampleClassTests
{
[Fact]
public void TestSaySomething()
{
string expected = "Something";
string actual = ExampleClass.SaySomething();
Assert.Equal(expected, actual);
}
// etc.
}
}
I execute the above tests at the command line with the command dotnet test.
In order to initialize any static class or static members of a class you can use static constructors. So, you can update your code as follow:
using System;
using System.Diagnostics;
using System.IO;
namespace Example.Shared;
public static class ExampleClass
{
static ExampleClass()
{
Trace.Listeners.Add(
new TextWriterTraceListener(File.CreateText("log.txt"))
);
Trace.AutoFlush = true;
}
public static string SaySomething()
{
Trace.WriteLine($"I'm gonna say something");
return "Something";
}
// etc.
}
For more details check:
C# static class constructor
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
BTW, I've also updated code to use the newly introduced file scoped namespace. Less indentation.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/file-scoped-namespaces
I have created a class and self initialized it in the file - is this the best way to use it? I have another Constant class that I can use but I am unable to use this for some reason in my project, do they need to be consts?
File: test.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DH.Models
{
public class test
{
public string testSourceCollection { get; set; }
public string testSourceKey { get; set; }
public string testSourceDatabase { get; set; }
public string testSourceCluster { get; set; }
public string testSourceTimestamp { get; set; }
public test[] testDetails = {
new test{
testSourceCollection = "SourceCollection",
testSourceDatabase = "SourceDatabase ",
testSourceKey = "SourceKey ",
testSourceTimestamp = "SourceTimestamp "
},
new ProviderRecon
{
testSourceCollection = "testSourceCollection2",
testSourceDatabase = "testSourceDatabase2",
testSourceKey = "testSourceKey2",
testSourceTimestamp = "testSourceTimestam2",
testSourceCluster = "testSourceCluster2"
}
};
}
}
I would like to use in my Worker.cs file as such
public class Worker : BackgroundService
{
var test = test.testDetails;
Console.WriteLine("2nd test: " + test.testSourceCluster )
//Prints "2nd test: testSourceCluster2"
}
You probably want testDetails to be static. You can't access (non-static) members using a type. Change public test[] testDetails = ... to public static test[] testDetails =...
However, you have a lot of non-standard namings there, which make this code confusing to read. The class test should be called Test instead. The line var test = test.testDetails; is hard to read otherwise (and probably won't compile). Same is true for your Worker class. That piece of code won't compile.
Every time when you create an instance of your class, testDetails property is initialized with new array. If you create 1000 instances for each instance testDetails is initialized with new array.
You can use static field/property to avoid create multiple instances with the same array. static keyword
Or use static readonly property/field to avoid create multiple instances with the same array. static readonly properties/fields can be initialized with static constructors. Static constructors
I'm trying to find all classes that implement a given interface with a method of "Execute". That method would do something different for each class, but return a result of success with a message. The original class that is finding and executing those methods would then return a JSON list of those results to the front end to display.
Essentially the end product would be a user navigates to a page, clicks a button and has a progress bar run that indicates several jobs are being executed.
My understanding with C# is beginner/intermediate. I think I need an interface that has a method called "Execute". And then for any job I have, I'd implement that method. My problem is now understanding how do I make it easy to get results from these jobs in a consistent format that can be parsed from the front end?
I've created a sample console app to focus on just the job portions with the following:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ConsoleApp1.Diagnostics;
namespace ConsoleApp1
{
class Program
{
public static void Main(string[] args)
{
IEnumerable<Type> allTypes = GetSubtypes<IJobTask>(Assembly.GetExecutingAssembly());
foreach (var type in allTypes)
{
//Just printing out the names now to see if the reflection works
Console.WriteLine(type.Name);
Console.WriteLine("----");
}
Console.ReadKey();
}
private static IEnumerable<Type> GetSubtypes<T>(Assembly assembly)
{
var types = from t in assembly.GetTypes()
where typeof(T).IsAssignableFrom(t)
select t;
return types;
}
}
}
IJobTask.cs
namespace ConsoleApp1.Diagnostics
{
public interface IJobTask
{
JobResponse Execute();
}
}
TestJob.cs
namespace ConsoleApp1.Diagnostics.Jobs
{
public class TestJob : IJobTask
{
public JobResponse Execute()
{
// Would actually call out to DB to run queries. Instead this is an example
var jobResponse = new JobResponse {Message = "This was successful", Success = true};
return jobResponse;
}
}
}
JobResponse.cs
namespace ConsoleApp1
{
public class JobResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
}
I can get the list of classes now, but I'm a bit lost on how to execute the method in each class. I'd like this to be an easy solution to where in the future I can just create a new class that implements this interface, and define the job execution method and it's good to go.
I am new to Stack Overflow and a neophyte programmer. I am trying to build in Visual Studio 2010 C# someone else’s code as a learning opportunity. I am unable to figure out why I get the following three errors in the four classes (line 50, 59, 67, & 75) at the bottom of the attached stub code (I stripped out from the original program everything not germane to the errors):
1. “c_basic_object” Method must have a return type
2. “:” ; expected
3. “(p_name)” Invalid token ')' in class, struct, or interface member declaration
4. “p_name” The type or namespace name 'p_name' could not be found (are you missing a using directive or an assembly reference?)
The code is almost identical to the Employee and Manager classes in Andrew Troelsen’s Pro C# 2005 book in Chapter 4.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestStub
{
class Program
{
static void Main(string[] args)
{
String strTest1 = "This is a string #1";
String strTest2 = "This is a string #2";
c_basic_object objBasic = new c_basic_object(strTest1);
Console.WriteLine(objBasic.m_name);
c_abstract_button_widget objButton = new c_abstract_button_widget();
Console.WriteLine("Test, Test, Test");
Console.ReadKey(true);
Console.WriteLine();
}
}// End class Program
public class c_basic_object
{
public string m_name = String.Empty;
//Constructor create_basic_object( p_name)
public c_basic_object(string p_name)
{
m_name = p_name;
}
// create_basic_object
//Constructor construct_empty()
public c_basic_object()
{
}
// construct_empty
//# Destructor Destroy()
~c_basic_object()
{
}
} // End class c_basic_object
// -- definitions only for the Virtual Abstract functions in the factory
public class c_abstract_button_widget: c_basic_object
{
public c_basic_object(string p_name) : base(p_name)
{
//Console.WriteLine("Inside c_abstract_button_widget ");
}
} // end c_abstract_button_widget
// c_abstract_button_widget
public class c_abstract_label_widget: c_basic_object
{
public c_basic_object(string p_name) : base(p_name)
{
}
} // end c_abstract_label_widget
// c_abstract_label_widget
public class c_abstract_draw_surface_widget: c_basic_object
{
public c_basic_object(string p_name) : base(p_name)
{
}
} // end c_abstract_draw_surface_widget
// c_abstract_draw_surface_widget
public class c_abstract_scrollbar_widget: c_basic_object
{
public c_basic_object(string p_name) : base(p_name)
{
}
} // end c_abstract_scrollbar_widget
}// End namespace TestStub
The problem is here:
public class c_abstract_button_widget: c_basic_object
{
public c_basic_object(string p_name) : base(p_name)
{
//Console.WriteLine("Inside c_abstract_button_widget ");
}
}
To declare a constructor, you have to specify the class name - but you've written c_basic_object. You meant:
public class c_abstract_button_widget: c_basic_object
{
public c_abstract_button_widget(string p_name) : base(p_name)
{
//Console.WriteLine("Inside c_abstract_button_widget ");
}
}
You have the same problem in your other subclasses too.
Separately, you should absolutely start following the .NET Naming Conventions. In this case, your classes should be:
BasicObject
AbstractButtonWidget
AbstractLabelWidget
AbstractScrollbarWidget
... although given that your "abstract" classes aren't actually abstract, you possibly want to rename them more... and possibly your BasicObject should be WidgetBase (or AbstractWidget, and actually abstract...)
Your parameters should just be name instead of p_name.
I'd also recommend keeping all fields private (I'd ditch the m_ prefix as well, but if the field is private that's not so bad) - you may want to expose the name as a property.
Additionally, you hardly ever need finalizers/destructors in C#. Definitely don't start adding them until you really, really know that you need one.
“c_basic_object” Method must have a return type
You are trying to create a constructor in the derived class, but constructors should be named after the containing class, not the base class. The compiler thus treads it as a method called c_basic_object, which must have a return type.
That should fix the other compiler errors as : base(p_name) is not valied syntax for a method.
Just rename your constructors:
public class c_abstract_button_widget: c_basic_object
{
public c_abstract_button_widget(string p_name) : base(p_name)
{
//Console.WriteLine("Inside c_abstract_button_widget ");
}
}
public class c_abstract_label_widget: c_basic_object
{
public c_abstract_label_widget(string p_name) : base(p_name)
{
}
}
public class c_abstract_draw_surface_widget: c_basic_object
{
public c_abstract_draw_surface_widget(string p_name) : base(p_name)
{
}
}
public class c_abstract_scrollbar_widget: c_basic_object
{
public c_abstract_scrollbar_widget(string p_name) : base(p_name)
{
}
}
Other suggestions:
Get rid of the empty "destructor". It is rarely needed in C# (and called a "finalizer" in some contexts)
Read up on naming standards. C# is Case-sensetive so camel case is preferred to separation by underscores
im trying to understand the get and set properties for fields, and run in to this issue, can somone explaine to me why i had to make the int X field Static to make this work?
using System;
namespace ConsoleApplication1
{
class Program
{
public static int X = 30;
public static void Main()
{
var cX = new testme();
cX.intX = 12;
Console.WriteLine(cX.intX);
cX.intX = X;
Console.WriteLine(cX.intX);
Console.ReadKey();
}
}
class testme
{
public int intX
{
get;
set;
}
}
}
Because you were using the field in a static context, in this case the method publicstaticvoid Main. Since your Program class just runs statically there is no instance and therefore you can't access any instance members.
because it is used in a static method
Since Main is static, you cannot access non-static instances from outside of it.