i want to pass a value from a variable from a project to another after referencing project B to A, after referencing, i still don't know how to read it
//Project A
namespace projectA{
public partial class hello : Form
{
public string value;
}
}
}
and for Project B
using projectA{
namespace projectB{
public string value2 = value;
}
}
please help :(, i already added project A to B through add reference and when i type projectA.... there is only one method shown which is the partial class
It sounds to me like you want to declare a static class member, you can do it like this:
public partial class hello : Form
{
public static string value;
}
And then you access it with hello.value, beware that this is bad design, by doing things like this you are going to make code that is hard to understand and hard to maintain.
Of course maintainable code is not something you will accomplish if you are learning so that's not a big deal, you should first understand the basic concepts and learn what does it mean for something to be "static", what does it mean to "instantiate" a class, what are interfaces, abstract classes, events, delegates, lambda expressions, inheritance, extension methods, properties and so on
--EDIT--
Just noticed how wrong the code in projectB is (not valid C#), see if you can understand the code below:
using projectA;
namespace projectB{
class YouMustHaveAClass { //C# does not allow you to declare variables that belong to no class
public string value2 = hello.value;
}
}
Related
After attempting to research C# namespaces further (coming from a c++ background) I think I understand the purpose of namespaces in general - to organise classes for the user, and to avoid conflicts. This practise, I imagine, still holds just as true for programs as it does for libraries.
What I don't understand is why exactly classes housing the Main() function would need to be part of a namespace.
I can't imagine that the main function would need to be called elsewhere for any reason, so organisation and conflict prevention ought not to be the reason.
Is it simply to show other developers what namespace to use throughout the rest of the program's classes? Or is there some deeper reason for it that is going over my head?
What I don't understand is why exactly classes housing the Main() function would need to be part of a namespace.
For sake of simplicity, we're going to assume that the class that contains Main() is called Program.
The Program class does not need to be in a namespace. For example, explicitly declaring the class:
// Program.cs
public class Program {
public static void Main(string[] args) {
System.Console.WriteLine("hi");
}
}
namespace MyNamespace {
public class Data {
public int Val {get;set;}
}
}
or using Top Level Statements
// Program.cs
System.Console.WriteLine("hi");
namespace MyNamespace {
public class Data {
public int Val {get;set;}
}
}
SharpLab (the links above) shows you what the compiler will output, and in both the Program class doesn't exist inside a namespace, even though other classes will.
And for the record, this is not limited to the Program class. You can put any/all of your types in the "global" namespace. You just lose the "categorization" benefit of namespaces.
I can't imagine that the main function would need to be called elsewhere for any reason
I'd agree. Normally you'd let the .Net runtime call your Main method. I'm sure you can think of some reason to do so, but really that's up to the architecture of your application. One maybe valid use case would be automated testing with a testing framework (xUnit, MSTest, etc) in a sibling assembly.
Now, say you did want to call the Main method yourself, as long as the Fully Qualified Type doesn't conflict with something else, you can still call it just like normal.
public class Program
{
public static void DoThing() { }
}
namespace MyNamespace
{
public class Data
{
public void ActivateDoThing() => Program.DoThing();
// or, if you run into a conflict
public void ActivateDoThing() => global::Program.DoThing();
}
}
Is there a reason for giving the class holding Main() a namespace in C#?
This is due to the editor you're using. Except for the Top Level Statements feature, when you create a new project with the "Console Application" template, it will have the Program class wrapped in a namespace, which is consistent with creating a new code file for a new class. This is just a decision the authors of the template have chosen, but at least it does follow the rule that every file has a namespace block. Familiarity can enhance readability, even if its inefficient.
That's really the point of the Top Level Statements feature - get rid of all the boilerplate. Technically, you don't need a namespace for the entry point class - so get rid of it. Most of the time, you don't add anything to Program besides the Main method, so don't require the user typing the class or method signatures. Just let the user get to the Main logic as fast as possible and the compiler can generate the rest.
That's really about it. Why is the namespace there? Mostly for consistency. Does it need to be there? Nope, not at all.
There is a bit of C# syntax that I don't understand.
I am on the receiving end of a couple of classes. Simplified, let's say it's this
public class ParentClass
{
public ParentClass();
public RandomEnumerated Random_Enumerated; //No get/set. Relevant?
}
public class ReceivedClass : ParentClass
{
public ReceivedClass();
public char Random_Field { get; set; }
}
When I do this
public class ExtendedReceivedClass : ReceivedClass
{
public ExtendedReceivedClass();
public char A_New_Random_Field_of_My_Own { get; set; }
}
I get hit by the error
ExtendedReceivedClass.ExtendedReceivedClass() must declare a body because it is not marked abstract, extern, or partial FuelTaCSClient
So instead of being able to do what the parental classes do
public ParentClass();
or
public ReceivedClass();
I have to do this
public LocalWreckerVehicleClass() {}
So my question is
a
Is the "public ReceivedClass();" in ReceivedClass the constructor? Same for ParentClass.
b
If it is, why can they do a shortcut version but I can't
or
if it isn't, what is it?
"I am on the receiving end of a couple of classes" -- I think you're looking at those classes using Visual Studio's "Go To Definition" or similar, and they're defined in another DLL?
You'll notice that Visual Studio is showing you method signatures, but not the bodies of the methods: when all it has is a DLL, it's easy to get the signatures, but harder to get the original C# code which was used to build the DLL. This is just intended to give you an overview of what methods are available, and it's not supposed to be valid C#.
public ParentClass(); is not valid C#. It's the signature of a constructor (showing that there's a public parameterless constructor), but when you define a constructor in C# you need to provide a body:
public ParentClass()
{
// ...
}
I am going to accept this as the answer because it seems to make the most sense. I have no trouble believing that when I ask VS to tell me what is in a parent class that it will give me an abbreviated and slightly askew version of what's actually in it.
I am doing a hard search for the parent class by name using a third-party search tool and if I see anything that either affirms or refutes this conclusion I will post an update.
Thank you to everyone who helped! And canton7 - thank you and have this upvote!
I am trying to achieve something specific in c# and I don't know if it has a name (or even if it's good practice). I tried to simplify the code as much as possible because this is a generic problem (no pun intended, what I mean by that is that it doesn't depend on the rest of the implementation)
Basically I have a generic class Class1, a class A, a class B that inherits from A, and another class Class2 that inherits from Class1 with B as the generic parameter.
The issue is that I get an error "cannot convert from 'Class2' to 'Class1'" when I try to cast.
I tried different combinations and have spent hours and checked dozens of links but so far I can't seem to find an answer to this exact problem. Keep in mind I am fairly new to programming (a few years but I learned by myself)
public class Class1<T> where T : A
{
public string name;
}
public class Class2 : Class1<B> { }
public class A { }
public class B : A { }
//if I change the parameter type to Class1<B>, but that defeats the purpose
//of being able to call this function with any class that extends Class1
void TestFunction(Class1<A> test)
{
Debug.Log(test.name);
}
//I basically want to do this
var instance = new Class2();
//I can't do this because instance is of type Class2 but can't be converted
//to Class1<A>
TestFunction(instance);
I want to be able to have classes that extend class1, like class2, with parameters that extend A, like B, but for a reason that I can't quite grasp it doesn't work this way.
Thanks for any help! I'm kinda in over my head and feel like I will never find a solution that works at my level.
To get this one working you'll need to setup the function in a generic fashion providing everything the compiler needs to resolve it as A. Not exactly nice to have to restate the constraints but it works.
static void TestFunction<T>(Class1<T> test) where T : A
{
}
This was a general question asked by a colleague of mine....
Is it possible to "outsource" code, and then call it in the main class (e.g. Form1.cs)?
This originates from the fact that he wants to organize his amount of code better than with regions, in the main class.
My first thought was - of course it is!
Use static Extentions, reference it to the main class, and call it through this.Method().
But he meant something like the "include" pattern in PHP....
Is that even possible?
he wants to organize his amount of code better than with regions, in the main class.
You can use partial classes to split the implementation of a single class into multiple (and perhaps more manageable) source files.
In File1.cs:
public partial class MyClass {
public void F() { ... }
}
In File2.cs:
public partial class MyClass {
public void G() { ... }
}
MyClass now has two methods, F and G.
You can externalize using partial classes or decouple it using c# assembly (dll).
I have a solution with two projects each producing a separate dll that is used by another windows application. Each of those projects has a class called MyActions with only one method like so
Project1
public class MyActions
{
public SomeTypeA DoJob(string str1, string str2)
{
}
}
Project 2
public class MyActions
{
public SomeTypeB DoJob(string str1)
{
}
}
The two return types of these two classes are as below
public class SomeTypeA
{
public string stringA { get; set; }
public int someInt { get; set; }
}
public class SomeTypeB
{
public string someStringA { get; set; }
}
The method DoJob in the both the classes of these individual projects have almost 80% code that is the same. Project1 is the one whose MyActions class's DoJob method has some extra bits specific to only Project1.
Now here is the twist.. Project1 is eventually going to be scrapped and its dll will no longer be used.I want to write the code in the best possible way that ensures there is no repeat of code and so that I dont have to make any modifications to remove any un-required code in Project2 once Project1 is discontinued.
I was thinking of using inheritance and overriding the DoJob method. How would that work if their return types are different and they have different input parameters? Perhaps push one of the parameters from Project1's MyActions class to its constructor? I was also thinking of adding a link to Project2's MyActions class in Project1. But not sure about how to go ahead with implementing that and not repeating myself or possibly running into unforeseen problems later. Any tips, suggestions?
If (and only if) the parameters and the return types of the two methods in the two classes are actually different, factor out the code that is line-for-line identical, assuming it is one block, and just create a static method in a new static class, passing the parameters necessary for the common code.
If there are multiple blocks, just have multiple methods.
Call these methods as appropriate from each of the original methods.
If you wanted to create a hierarchical relationship between these classes, which you should only do if it is logical to do so, just make them both inherit a common type, and make the method above a protected method of that common class. Then just call it from the original methods.
Your thought about inheritance is a good one. From your question in read between the lines that you were considering to let Project 1 inherit from Project 2. That's a possibility but probably not the best solution. Here is what I would suggest.
Create a super class for MyActions that both projects extend. Into this class you can move all the code that is shared across both projects (your 80% code of the method). The specific implementations in your MyAction in each project then implement the DoJob method as needed and make use of the provided methods from the super class.
Once you scrap project 1 there will be no changes that have to be made to project 2's code. You end up with a super class though that you do not really need any more in that case. However you won't be repeating yourself anywhere.
I am not yet familiar with the exact differences between java and C# so bear with me if there are differences. This is what code might look like in java.
abstract class AbstractMyActions {
protected SomeType commonMethodForBothProjects() {
...
}
}
public class MyActionsA extends AbstractMyActions {
public SomeType doJob(SomeParameter ..., SomeParameter ...) {
$this->commonMethodForBothProjects();
// Additional steps
}
}
You get the idea.
public class MyActions
{
public ISomeType DoJob(ISomeParam item)
{
}
}
public class SomeTypeA : ISomeType
public class SomeTypeB : ISomeType