|
class class1
{
public int a;
}
form1 :
class1 s=new class1();
s.a=10
form2:
class1 c=new class1();
messageBox.show(c.a.tostring()); // I want to see 10 here
|
|
|
|
|
SajjadZare wrote: I want to see 10 here
only people unfamiliar to object orientation would expect or accept that to happen.
you have two statements containing new class1() which means two objects get created, i.e. two different instantiations of the class1 class. Now if one object is changed, that should not reflect on its siblings. If your house has ten windows and you happen to break one of them, you would not like all of them to break into pieces, would you?
There are a couple of ways to get what you want. They all have one thing in common: they create only one instance of the thing that needs to be accessed at several locations, instead they pass a reference around. And there is a plethora of articles on the subject, maybe this one[^] can help you.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read formatted code with indentation, so please use PRE tags for code snippets.
I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).
|
|
|
|
|
Because what you are doing is creating two separate instances, you can only do this if there is a single variable "a" that is common to all instances of "class1". You do this with the static keyword.:
class class1
{
public static int a;
} You can then use it in any instance.
form1:
class1 s=new class1();
class1.a=10
form2:
class1 c = new class1();
MessageBox.Show(class1.a.ToString());
But you can't use "s.a" or "c.a" because it would look confusing - you might think that "a" was specific to the particular instance of class1 rather than shared between them.
It's a bit like cars: They can all have a colour, but they don't share it: YourCar has a different colour (blue) to MyCar (red). They do share common information: NumberOfWheels (4)
So you can't say "What colour is a car?" but you can say "How many wheels has a car?"
You can say "What colour is my car?" or "What colour is your car?" because this specifies exactly which car you are talking about.
If you feel you must access "a" via an instance, you can declare a property which does that for you (but it isn't really recommended):
class class1
{
private static int a;
public int A
{
get { return a; }
set { a = value;}
}
} You can now access "A" via "s.A" and "c.A" to get the same value which is shared between all instances of class1.
Did you know:
That by counting the rings on a tree trunk, you can tell how many other trees it has slept with.
|
|
|
|
|
I'm not so sure this is a good suggestion. Maybe what he wants to share deserves to be static and unique, but I didn't get a clue in that direction; simply adding "static" to get something to work is not OK in my books. As I guess you read similar books, maybe I missed something?
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read formatted code with indentation, so please use PRE tags for code snippets.
I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).
|
|
|
|
|
Oh I agree - static is best reserved for when it is really needed - but since I haven't a clue what he wants to do with it, I didn't want to just leap in with "you can't do it", so I tried to explain a bit as to when you use static. I don't think I have used static for anything other than methods in C# yet - just haven't found the need...
I started writing my response before you posted yours, and saw yours there after I pressed "Post Message". I'm just a slow typist sometimes - especially when the wife is trying to use the internet so I have to stop and sort her out every few minutes.
Did you know:
That by counting the rings on a tree trunk, you can tell how many other trees it has slept with.
|
|
|
|
|
Oh great, blame the wife for giving an overly static/Shared and slow response.
Most of my classes do have a couple of static data members, often for statistical purposes (counting or holding a list of all instances), and for logging parameters. But these are just tools, they don't reflect application-domain properties.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read formatted code with indentation, so please use PRE tags for code snippets.
I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).
modified on Friday, June 4, 2010 5:55 PM
|
|
|
|
|
She is a natural VB user - she finds out about a tool, then she uses it for everything.
Everything can be a hammer, if you hit it hard enough...
Did you know:
That by counting the rings on a tree trunk, you can tell how many other trees it has slept with.
|
|
|
|
|
Now it all makes sense; I have fixed my earlier message accordingly.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read formatted code with indentation, so please use PRE tags for code snippets.
I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).
|
|
|
|
|
What you need is a static class that can be shared between forms. You can use Session or Application state for this if you are using ASP.NET, however, if the object is large it may not be the best way to handle it.
You can also pass the value you are interested in from form1 to form2 via properties, events, constructors.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Hello all,
I have configured my logging application block as follows, using Enterprise Libaray 4.1 (in app.config):
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<logFilters>
<add
name="LogEnabled Filter"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
enabled="true"
/>
<listeners>
<add
name="Rolling Flat File Trace Listener Debug"
fileName="Logs/Debug.log"
header="------HEADER-------"
footer=""
formatter="Text Formatter"
rollFileExistsBehavior="Overwrite"
rollInterval="Day"
rollSizeKB="10000"
timeStampPattern="yyyy-MM-dd"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None"
filter="Verbose"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
/>
<add
name="Rolling Flat File Trace Listener Unprocessed"
fileName="Logs/Unprocessed.log"
header="-------------"
footer=""
formatter="Text Formatter"
rollFileExistsBehavior="Overwrite"
rollInterval="Day"
rollSizeKB="10000"
timeStampPattern="yyyy-MM-dd"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None"
filter="Verbose"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
/>
<add
fileName="Logs/RawLogHistory/RawLogHistory.log"
name="Rolling Flat File Trace Listener Full History"
header=""
footer=""
formatter="Text Formatter"
rollFileExistsBehavior="Overwrite"
rollInterval="Day"
rollSizeKB="10000"
timeStampPattern="yyyy-MM-dd"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None"
filter="Verbose"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
/>
</listeners>
<formatters>
<add
name="Text Formatter"
template=" {severity} [{timestamp}] {message}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
/>
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Rolling Flat File Trace Listener Debug"/>
</listeners>
</add>
<add switchValue="All" name="Debug">
<listeners>
<add name="Rolling Flat File Trace Listener Debug"/>
</listeners>
</add>
<add switchValue="All" name="Exception">
<listeners>
<add name="Rolling Flat File Trace Listener Release"/>
<add name="Formatted EventLog TraceListener Formicary"/>
</listeners>
</add>
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events"/>
<notProcessed switchValue="All" name="Unprocessed Category"/>
<listeners>
<add name="Rolling Flat File Trace Listener Unprocessed"/>
</listeners>
</notProcessed>
<errors switchValue="Information" name="Logging Errors & Warnings">
<listeners>
<add name="Rolling Flat File Trace Listener Debug"/>
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
Everything works fine.
The only issue i have, is with the "Unprocessed Category" special source.
Reading the documentation from msdn for EntLib L.A.B., i undestood that when you try and log to a Category that is not specified, that LogEntry is directed to the Unprocessed Category source.
In the above example though, if i log a Verbose message, and define the category in the LogEntry to be let's say "Undefined" (which is not specified in the configuration), i loose that LogEntry completely. Ideally, when the application attempts to log, it should do the following steps:
-Get the LogEntry and pass it through the logfilters.
-If it passes through the logfilters, find the category that the logentry specifies, and pass it to the listeners in that category
(in our current case, category is "Undefined")
-If you can't find the category specified in the LogEntry,go to the "Unprocessed Category" special source and log it to the listeners specified in there.
BUT:
!!Last step is never executed. I do not get the log in my flat file!!
NOTES:
-I have double checked, and the filters for both
the listeners and the categories are not blocking the LogEntry because of the level of message (verbose, information, etc...)
-The other special sources ("All Events" and "Logging Errors & Warnings") work fine.
Any suggestions on why this is the case?
Any hints would be appreciated.
Regards,
Shtel
|
|
|
|
|
Hi Experts,
This should be a very trivial question for you guys.
I have an object with me. This object is an object of a class who is inherting from an abstract base class. I want to know what is that base class.
Let me give you an example
Say I have 2 abstract base classes namely MyBaseClass1 and MyBaseClass2 which is inheriting from a Form class so my code would be something like this.
abstract public class MyBaseClass1 : Form
{
abstract public void MyMethod1();
}
abstract public class MyBaseClass2 : Form
{
abstract public void MyMethod2();
}
I have many forms which are inheriting from these base classes. For example
public partial class Form1 : MyBaseClass1
{
public Form1()
{
InitializeComponent();
}
public override void MyMethod1()
{
MessageBox.Show("mymethod1");
}
}
These forms will be opened in an MDI form. I want to know which is my active form. This i can get from the property of the MDI form ActiveMdiChild . But this property will return me a Form object. I want to know what is the base class of this form object i.e. whether it is MyBaseClass1 or MyBaseClass2. I also want to create an object of this base class if possible.
Please do let me know if I hv not explained my query properly.
Please help!
Thanks in advance!
Regards,
Samar
|
|
|
|
|
if (ActiveMdiChild is MyBaseClass1)
{
// your code hier
}
|
|
|
|
|
You have a few options, you can as previously stated use the is keyword and see if it's the type you are looking for.
An alternative is to actually look at the BaseType :
Type t = ActiveMdiChild.GetType();
Type baseClass = t.BaseType;
object something = Activator.CreateInstance(baseClass);
However, unless there is a common base class that you can cast to so that you can use it then you are back to checking the actual type and casting to that.
So depending on what you have and what you need you can either have a series of if statements checking for the types or the above method where you will be able to create and use your base class without necessarily knowing exactly what it is.
My current favourite quote is: Punch them in the face, see what happens!
-SK Genius
|
|
|
|
|
Hmm.. This looks good but i wont get the methods of the base class object in the intellisense here. Is there a way of getting that too? Maybe i am asking for too much here.
Regards,
Samar
|
|
|
|
|
Check out this article:
The case for a generic C# converter using operators[^]
.45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
|
|
|
|
|
I am having an issue with this. I need to create a folder in the current users application data folder to store settings but I cannot. Every time I try to use Directory.CreateDirectory(Environment.SpecialFolder.MyDocuments + "/JFE/Settings") Or anything else under SpecialFolder it will just create a folder in the application's directory with a name like Personal then inside this directory it will make the folders I requested. Why does it do this? I printed out the string for the special folder and looked at it and it is correct but for some reason it creates my folders in the current program's directory.
Y*Live Long And Prosper*Y
|
|
|
|
|
Try this:
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "JFE/Settings"))
Good luck
PS: The big change is Environment.GetFolderPath. Path.Combine I just inserted because it's better to use that than concatenate the path using "+"
|
|
|
|
|
Worked! Thanks!
Y*Live Long And Prosper*Y
|
|
|
|
|
Of course! Learn from the master, my young jedi...
|
|
|
|
|
i have developed a simple c# desktop windows app when i take it to another pc its color automatically changed to black or another , can any one help that how can i prevent from this prob
|
|
|
|
|
With that little information, no - no-one can help.
We would need a better description of the problem, and probably a small fragment of relevant code (use the "code block" widget to preserve formatting) to show us what you are doing.
Did you know:
That by counting the rings on a tree trunk, you can tell how many other trees it has slept with.
|
|
|
|
|
Windows controls appereance by default depends on selected theme in windows.You can avoid it by creating your own theme independant styles for each of them.Similar job has already been done for MFC here at cp ^.
Life is a stage and we are all actors!
|
|
|
|
|
hello every one. am trying to create Image from byte array in my page. First i create the image by System.Drawing.Image then am trying to convert System.Drawing.Image to System.Web.UI.WebControls.Image. but the compiler says "Cannot convert type 'System.Drawing.Image' to 'System.Web.UI.WebControls.Image'". So any one please help me.Thxs.
|
|
|
|
|
At first you have choosen wrong forum to post your question.You should post it to ASP.NET forum.
This article explains how to solve it and lots more.
Life is a stage and we are all actors!
|
|
|
|
|
I want to register a hotkey(for example:Ctrl+Shift+A) to do such a thing:
When I press the hotkey, I hope it will input a sentence "Hello!" at the position of current cursor in a outer active window, such as Microsoft Word,NotePad,etc.
Now I have completed the registration of the hotkey with:
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool RegisterHotKey(
IntPtr hWnd,
int id,
uint fsModifiers,
Keys vk
);
.....
RegisterHotKey(Handle, 150, 2|4, Keys.A);
.....
private void ProcessHotkey(Message m)
{
IntPtr id = m.WParam;
string sid = id.ToString();
switch (sid)
{
case "150": SayHello(); break;
.....
}
}
.......
private void SayHello()
{
MessageBox.Show("Hello!");
}
It works well! When I press Ctrl+Shift+A ,a messagebox will say "Hello!". But how to get the current active window, and input the text to current cursor, no matter where the cursor is and which application it is in?
|
|
|
|
|